PowerShell for-each loop output to file


How do I output/append the contents of this foreach loop to a text file?

The following below is not working out.


All this does is saves the output of your foreach loop into the variable $output, and then dumps to data to your file upon completion.

Note: Write-Host will write to the host stream, and not the output stream. Changing that to Write-Output will dump it to the $output variable, and subsequently the file upon loop completion.

The reason your original code isn’t working is that you’re not actually writing anything to the file. In other words, you’re piping no data to your Out-File call. Either way, my approach prefers a cache-then-dump methodology.


PowerShell for-each loop output to file by licensed under CC BY-SA | With most appropriate answer!

Leave a Reply