July 10th, 2018

PowerShell PowerTip: What you should know about streams

Kory Thacher
Premier Field Engineer

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
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!

Author

Kory Thacher
Premier Field Engineer

I've been a PFE since 2012, working with various technologies. I live in the modern applications domain, doing work in UWP apps, .NET, Unity, DevOps, and of course PowerShell. I've been teaching PowerShell related workshops very frequently for years, and I really enjoy getting the opportunity to explain a topic or learn something new from my colleagues. I enjoy scripting because of how fast and interactive it can be, and I love getting interesting problems to work on with customers. ...

More about author

0 comments

Discussion are closed.