Share via

Saving powershell output not working

Jake_0981 1 Reputation point
2021-11-12T15:10:04.143+00:00

Hi everyone,

I am using a PowerShell output, but seem to have trouble saving it to a file.

I am using the following command. I've got everything apart from saving the output.

Any help would be greatly appreciated! Thank you! :)

$names = Get-content "C:\Users\Admin\Desktop\Sites\prss.txt"

foreach($name in $names){
if (Test-Connection -ComputerName $name -Count 1 -ErrorAction SilentlyContinue){
Write-Host "$name is up" -ForegroundColor Green
}
else{
Write-Host "$name is down" -ForegroundColor Red
}
}
{$output | Out-File 'C:\Users\Admin\Desktop\Sites\results.txt'
Start-Sleep -Seconds 15}

Windows for business | Windows Server | User experience | PowerShell
0 comments No comments

3 answers

Sort by: Most helpful
  1. Rich Matheisen 48,116 Reputation points
    2021-11-12T16:05:16.027+00:00

    You don't need the $output variable at all.

    Also, the Write-Host cmdlet sends its output directly to the host, not to the "Success" stream (which is where you want it)

    Get-content "C:\Users\Admin\Desktop\Sites\prss.txt" |
        ForEach-Object {
            if (Test-Connection -ComputerName $_ -Count 1 -ErrorAction SilentlyContinue){
                Write-Host "$name is up" -ForegroundColor Green
                "$_ is up"
            } else {
                Write-Host "$name is down" -ForegroundColor Red
                "$_ is down"
            }
        } | Out-File  'C:\Users\Admin\Desktop\Sites\results.txt'
    Start-Sleep -Seconds 15
    

    Was this answer helpful?

    0 comments No comments

  2. MotoX80 37,686 Reputation points
    2021-11-12T15:38:20.98+00:00

    There is nothing in the $output variable.

    $names = Get-content    "C:\Users\Admin\Desktop\Sites\prss.txt"
    $output = @()           # define empty array that we will add to
    foreach($name in $names){
        if (Test-Connection -ComputerName $name -Count 1 -ErrorAction SilentlyContinue){
            Write-Host "$name is up" -ForegroundColor Green
            $output += "$name is up"
        } else {
            Write-Host "$name is down" -ForegroundColor Red
            $output += "$name is down"
        }
    }
    $output | Out-File  'C:\Users\Admin\Desktop\Sites\results.txt'
    Start-Sleep -Seconds 15
    

    Was this answer helpful?

    0 comments No comments

  3. Benard Mwanza 1,006 Reputation points
    2021-11-12T15:18:46.84+00:00

    You can share the error you are getting.

    Meanwhile do this,

    Modify this line.

    $output | Out-File 'C:\Users\Admin\Desktop\Sites\results.txt'

    To this.

    $output | Out-File -FilePath C:\Users\Admin\Desktop\Sites\results.txt

    Was this answer helpful?


Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.