Understanding PowerShell’s $_ And $PSItem Pipeline Variables
Think you can do better? Show us!
Did you know why the PowerShell pipeline variable is a dollar sign and an underscore? Because the underscore looks like a pipe on its side. Useless trivia. I know. For some reason, the PowerShell team decided that wasn’t “user-friendly” enough and let all of these new whipper-snappers to PowerShell use $PSItem instead. They are exactly the same, people! I still don’t get some people.
Understanding Powershell's dollar underscore an dollar PS item pipeline variables. Quite simply they represent the current object in the pipeline. They are automatic variables created by PowerShell internally. So to show you what this means. I'll give you some examples first to have some data to work with I am going to load this array into memory and then we're going to send this array through this for each loop. And just simply write out dollar underscore for each one so this executed the line. This is dollar underscore for each one of those items sent from that array through that for each loop so again quite simply. This dollar underscore represents the current object in the pipeline so shorthand for dollar PS item, they are the same thing. And show you what I mean when I say the same thing. They're the same thing you get the same result, so they're interchangeable dollar underscore dollar PS item. A slightly more complex use of this automatic variable. Let's you access properties and functions of the object. That's passed through the pipeline so we can execute this little script to show you how this works. So this get service is sending all of its objects through the pipeline to this for each loop and we're doing a write output dollar underscore name and that's just the name property from the service objects and that prints, it out to the screen. So that is understanding Powershell's dollar underscore and dollar PS item pipeline variables.