PowerShell: Implementation of Anonymous Self Executing Function

JavaScript has this. It’s a little known secret that PowerShell can do this as well. Why is this significant? Well, there are several ways this can be incoporated into a program. One trick I’ve learned over the years is that anonymous function can be used in lieu of the infamous try/catch function, and much more. Scan my blog for more examples. Here’s a quick illustration for our current view:

.{
write-host "Statement 1";
$condition=Read-Host -Prompt 'Do you want execute Statement 2? (y/n)'
if (!($condition | Select-String -pattern 'y','yes','Y','Yes')){return}
write-host "Statement 2"; # This statement would only be called if the script has not reached the 'return' command
}

Leave a Reply

Your email address will not be published. Required fields are marked *