Exporting powershell output to text file

Question:

I have a foreach loop inside my powershell script with prints $output on the shell during each iteration. There are lot many outputs and the number of entries that the shell can display is limited. I am looking to export the output to a text file. I know how to do it in command line. How is it possible in a powershell though?

FYI, I am using a batch script from the command line to run the powershell script as

Answer:

You can always redirect the output an exe to a file like so (even from cmd.exe):

Within PowerShell, you can also redirect individual commands to file but in those cases you probably want to append to the log file rather than overwrite it e.g.:

As you can see, doing the redirection within the script is a bit of a pain because you have to do lots of redirects to file. OTOH, if you only want to redirect part of the output to file then you have more control this way. Another option is to use Write-Host to output info to the console meant for someone observing the results of the script execution. Note that Write-Host output cannot be redirected to file.

This is an example executed from CMD.exe

Source:

Exporting powershell output to text file by licensed under CC BY-SA | With most appropriate answer!

Leave a Reply