r/PowerShell • • Nov 17 '22

Question ELI5 "$_"

Attempting my way through "PS through a month of lunches" only experience being my A+.

They are just glossing over "$_"

Here is an example from the book.

Can someone break this down for me? They attempt to in the book but don't go in depth enough, so I would have no idea how to use this in a real scenario:

Get-Process | Format-Table Name, @{name='VM(MB)';expression={$_.VM / 1MB
➥ -as [int]}}

I just feel like this book goes leaps and bounds over what you just learned about. I just went from learning how to formatting a list to whatever... that is. Again, they *attempt* to explain what is going on here, but I have no idea what "{" are used for, why you would use them, when you would use them, etc.

132 Upvotes

61 comments sorted by

View all comments

102

u/GiulianoM Nov 17 '22

$_ represents the object(s) passed from the previous step in the pipeline.

In your sample, $_ would refer to the process(es) returned from Get-Process.

And $_.VM means the VM (Virtual Memory?) property of the process.

So by piping Get-Process into Format-Table, for each Process found, it will make a table with the Process Name, and the Process VM formatted as an expression with the column name "VM(MB)", Virtual Memory in Megabytes.

9

u/Mysterious-Ad-1541 Nov 17 '22

Do you have any trainings I can use to test this? I have read this over and over and do not understand.

14

u/Necoras Nov 17 '22

Consider this array:

$myArray = @(1,2,3,4,5,6)

You can do:

$myArray | ForEach-Object { Write-Host "$_" }

This is equivalent to:

ForEach ($myVar in $myArray){
    Write-Host "$myVar"
}

Personally I prefer the latter (and indeed, my team would reject the first on a code review) because it's a bit clearer, and "$myVar" is harder to miss than "$_" somewhere in the middle of a long line of code. It's also clearer what it is in a non-contrived example. "$myVar" isn't meaningful, but "$service" or "$process" or "$file" is.

1

u/retr0baD Nov 18 '22

Is $myVar a default variable in PowerShell for referencing array items?

3

u/ZaRx2048 Nov 18 '22

No, in a foreach you create a variable to represent each object/element in the array. You could call it $foo in $myArray. Example if you use $myFruits as an array you could use foreach($fruit in $myFruits)…

When I was in the early stages of learning the get-help and about pages were very helpful. Look up powershell about arrays.

2

u/overlydelicioustea Nov 18 '22

you can choose freely, name it however you want.