r/PowerShell • u/iamelloyello • 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
5
u/SomeCynicalBastard Nov 17 '22 edited Nov 21 '22
-- 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 inForEach-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-Tabletakes 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 toFormat-Table, and$_is automatically filled with the object passed down the pipeline.