Jawz84 / explainpowershell

PowerShell version of explainshell.com
https://www.explainpowershell.com/
MIT License
34 stars 1 forks source link

Explanation should be refined for '$_' in scriptblocks without pipeline. #87

Closed LaurentDardenne closed 1 year ago

LaurentDardenne commented 2 years ago

www.explainpowershell.com considers the automatic variables '$_' and '$PsItem' as linked to a pipeline. For the following examples this is not the case, at least not in the submitted code because the pipe character '|' does not exist. A beginner may therefore be disappointed by the explanation given so far. With :

switch (get-service | select-object status) { {$_.status -like "Running"} {$running++}}

From the PS v3 specification document (8.6 The switch statement): Switch :

on entry to each statement-block, $ is automatically assigned the value of the switch-condition that caused control to go to that statement-block. $ is also available in that statement-block's switch-clause-condition.

For throw :

Within a matching catch clause, the variable $_ contains a description of the current exception.

For trap {"Error found: $psitem"}

Within a trap statement the variable $_ contains a description of the current error.

There are also Winform and WPF eventhandlers, but that's off topic here :

$Form1.Add_FormClosing( { 
    # $this = sender (object)
    # $_ =  e (eventarg)

    ($_).Cancel= $False
} )

Note : The constructions submitted here are suitable because only one line can be entered.