What is $_ in Powershell?

It was in 2019. Dave was one of the new sysadmin guys in a big corporation in Tokyo. Before this job, he worked for a small company with a few Windows servers.

In the current work, he administrates a thousand servers. He decided to start using Powershell for automating his sysadmin tasks. Before, he never asked anyone for help, but someday everything changed.

One thing that helped him to write one-line Powershell code

Every day, Dave was learning something new in Powershell. When he wanted to learn a new Powershell topic, he found it on the Internet.

Once he read the article about the pipeline, and he wanted to get to know how to write one-line Powershell code. He has known that he needs pipe symbol (“|”) to connect many Powershell command in one line.

He had one problem. He didn’t understand what exactly means the $_ symbol. He found one person who explained everything.

What is $_

John was a senior Active Directory Administrator and working with Dave. It was the first person whom Dave could ask about everything in Powershell. John explained to Dave what is $_ symbol in Powershell.

$_ is like the shortcut to the past

John’s explanation was easy. He told Dave that the $_ symbol is like a shortcut to the past. In other words, it’s a shortcut to the result of the Powershell command ran before the pipe symbol (” | “).

$_ is the alias for $PSItem automatic variable and contains the current object in the pipeline object.

It’s useful for filter objects.

what is $_
what is $_
what is $_

Also, it’s useful for operate on all records from an array one by one.

what is $_

Conclusion

Finally, thanks to John, Dave understood the $_ symbol in Powershell. He knows how to write a one-line Powershell code. In his work, he met a lot of situations where he used this knowledge to faster do his administrative tasks. 

Now you can practice this topic. Below I added two exercises for you.

Exercise 1

Use Get-Command and Where-Object to filter commands started from ‘Get’ word. Share your result in the comments.

Exercise 2

Try to get the same result as below but using two commands – Get-Command and Foreach-Object. Share your result in the comments.

Get Access to Poshland Resources for FREE!!!

Signup now and receive an email once I publish new content.

I agree to have my personal information transfered to MailChimp ( more information )

I will never give away, trade or sell your email address. You can unsubscribe at any time.