Heisenberg
Heisenberg

Reputation: 123

How to output script to file?

I found a ping script which is useful, but I'd prefer to write the output to a txt or csv rather than using Write-Host to output to the PS console.

What is the best way of doing this?

Upvotes: 0

Views: 250

Answers (2)

Kenneth King
Kenneth King

Reputation: 126

Try adding the stdOut to an Array. Then write results at the end.

 #Define the array
 $myOutput = @()

 #Do something here"
 $myOutput += $myStdOut
 #Done with something
 $myOutput | out-file -FilePath c:\myOutput.txt -Encoding utf8 -NoClobber
 $cat c:\myOutput.txt

Upvotes: 1

Jeff Zeitlin
Jeff Zeitlin

Reputation: 10764

You will need to change the Write-Host to Out-File, or, better still, Out-Default. Using Out-Default will allow you to pipe the output to other cmdlets, and therefore allow you to handle the output differently on different occasions, depending on your particular need at the moment.

Write-Host bypasses the PowerShell pipeline, and effectively removes any objects it uses from the pipeline, making them unavailable for assignment or use by other cmdlets.

References:
Get-Help Write-Host
Get-Help Out-File
Get-Help Out-Default

Upvotes: 2

Related Questions