PowerShell PowerTip: What you should know about streams


PowerShell has a concept called Streams, which are the different places data can go (output, error, verbose, etc). You usually don't have to worry too much about these streams if you're just writing simple scripts, but it helps a ton to know:

  1. All streams are separate even if they all appear to be coming to the console for you.
  2. Assignment operators (like "=") only look at the output stream.
  3. If you don't tell PowerShell where to put data (such as just typing get-process) it defaults to the output stream.

What this means for you, as users, is that you can get a non-terminating error, and still do work on the successful output. Take a look at this:


$procs = get-process POWERPNT, powershell_ise, FAKE, audiodg

Write-host "Procs contains:"
$procs.name

</pre>
get-process : Cannot find a process with the name "FAKE". Verify the process name and call the cmdlet again.
At line:1 char:10
+ $procs = get-process POWERPNT, powershell_ise, FAKE, audiodg
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (FAKE:String) [Get-Process], ProcessCommandException
+ FullyQualifiedErrorId : NoProcessFoundForGivenName,Microsoft.PowerShell.Commands.GetProcessCommand

Procs contains:
audiodg
POWERPNT
powershell_ise

Notice that even though I received an error for the process "FAKE", only the non-errors were present in $procs. Using some basic error handling we could clean that up, hide the error message and log out what we didn't find.

If you want to learn more about these streams, let me know and I can write a more detailed blog post.

Hope that helps, tune in more often to get short and sweet PowerTips!

Comments (2)

  1. Dennis Rutherford says:

    You should probably use Write-Output and not Write-Host in the example.

    1. Kory T says:

      Doesn’t matter either way when looking at data in the host anyways 🙂

Skip to main content