HBoPS #8: Automatic variables in PowerShell

HBoPS #8: Automatic variables in PowerShell

So over the years I’ve worked with a few variables I took for granted, and I figured it was time to learn more about them! As always, I share that knowledge with you, my dear reader (now get me a muffin!).

What are automatic variables?

Automatic variables are variables (!SURPRISE!) that store state information for PowerShell. You do not need to do anything to get information in to these variables, it’s PowerShell that creates and maintains them.

$_ or $PSItem

You’ll probably have worked with this one before (notably if you’re running a | Where-object {$_ <something>} command). This is simply the current object in the pipeline, and allows for lots of nifty filtering and manipulations

$Error

This lovely variable contains all the error objects, or rather the most recent error objects that occurred. If you want to see the most recent error, use $Error[0].Do note that if you use an ErrorAction parameter of Ignore, any error received will not be added to the $error object.

$IsLinux, $isMacOS, $IsWindows, $IsCoreCLR

Lovely things that return a Boolean response depending on if you’re running PowerShell on Linux, MacOS, Windows, or if you’re running on the .NET Core Runtime.

$PID

Having struggled with different PowerShell tools running simultaneously and how to manage them (Kalvin, if you’re reading this, you know what I’m talking about!) $PID have offered a great deal of help with that. It contains the process identitfier of the process hosting the current PowerShell session.

This gives you a means to track PowerShell sessions, if you so desire.

$PSBoundParameters

This one is actually my most recent discovery and a very nifty one! Ever added parameters to a function and then needed to do a check to see if they were used? You probably did something like this:

So the major downside with this approach is that, if you’ve used the variable $Switch somewhere else (aka it exists in the session), you’re not going to have a pleasant day. Having to keep track of all those variables in large projects gets confusing. As it turns out, there is a better way…

You see, $PSBoundParameters contains key/value pairs of the parameters that are passed to your functions (scripts too!). This allows you to keep using common parameters, without having to worry about a randomly floating thing somewhere! There’s 3 different ways you can go about using this: