Output your ForEach into a file

Something that i always forget after spending a little while perfecting the contents of your ForEach loop is that eventually it’ll be necessary to output the content as Objects or into a file of some sort, whether thats before or after some manipulation. The answer to this is a very simple one, you need to store your ForEach in a variable and then reference that Output at the end of the ForEach scriptblock, like below:

$process = Get-Process

$output = foreach($line in $process){

Write-Output $line | select Handles, Id, ProcessName

}

$output | Sort-Object -Property ProcessName | ft

The $output variable will now contain the objects in your ForEach and you can do whatever you want with them.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s