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

Show parent comments

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/wisym Nov 17 '22

So it's for golfing the code?

3

u/ka-splam Nov 18 '22

So it's for golfing the code?

No more than your apostrophe is for golfing English.