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

5

u/SomeCynicalBastard Nov 17 '22 edited Nov 21 '22

Same as $PSItem. Contains the current object in the pipeline object. You can use this variable in commands that perform an action on every object or on selected objects in a pipeline.

-- https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_automatic_variables?view=powershell-7.2#_

I would add that $_ is also a placeholder in ForEach-Object 'loops'.

As for the curly braces, the main uses are:

  • ${name}, to use a variable. Usually we just write $name;

  • @{key1=val1;key2=val2;...}, to define a HashTable. You don't need semicolons if you use linebreaks;

  • { ... }, to define a script block. This is just a block of PowerShell code.

In your example, Format-Table takes a HashTable as aparameter, with keys 'name' and 'expression'. Expression takes a script block as a value. This script block is evaluated for each object that is passed down the pipeline to Format-Table, and $_ is automatically filled with the object passed down the pipeline.

6

u/sysiphean Nov 17 '22

Small correction:

$_ (or $PSItem) is a placeholder in ForEach-Object loops, but not foreach loops.

1

u/SomeCynicalBastard Nov 21 '22

Thanks, you're absolutely right. Wouldn't even make sense in a foreach loop :)

2

u/jpbras Nov 17 '22

"${name}, to use a variable. Usually we just write $name;"

Just a little note on this...

You want to use ${when variable have spaces} when the variable have spaces (or any special character) and ${c:\variableInAFile.txt) if you want to place the variable on any PSDrive recognizable by Powershell.

That's why {} are used on variables.