0

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?

3
  • 2
    Use PowerShell 5 and Write-Information. Then, redirect the Information stream to a file. Commented May 9, 2017 at 15:26
  • 1
    What version of PowerShell do you intend to run this on? Commented May 9, 2017 at 15:27
  • Do you still want syntax highlighting? Most easy solution will make you drop that. It is usually a good practice to allow cmdlets/functions to generate output and allow the caller to decide how to deal with it or suppress it. Having several streams allows you a lot of functionality here Commented May 9, 2017 at 15:40

2 Answers 2

2

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

Sign up to request clarification or add additional context in comments.

5 Comments

Read here that out-file should not be used in a loop.
@Heisenberg - That's a good argument against Out-File, agreed; I hadn't been thinking about performance as a priority - especially as I favor the Out-Default model, where I leave it up to the user of the ping script whether he wants it to go to file or to another cmdlet or wherever, at run time.
I can't seem to find a good example on how to use Out-Default in the context that I am looking to do with this ping script. Do you know of one?
I'm sorry; I'm not clear on what you're not understanding.
I did get my simple script to write the output to a text by substituting write-host with write-output and then piping it to out-file. I guess that's baby steps until I learn how to use array's as suggested by @Kenneth King. I do not like the format of the resulting output in the text file. I want to next explore using export-csv to write the output in a cleaner format with the hostname in one column and the status in another.
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.