September 1, 2015

PowerShell - ScriptBlock

The ScriptBlock is a special form of command. It can contains multiple lines of code. It is defined by braces. You can put the call operator to execute a scriptblock: 
& { "Get date: " + (get-date) }

The call operator normally runs only a single commands. With script block you can run multiple lines of instructions since scriptblocks can consist of any number of commands.
& {Get-Process | Where-Object { $_.Name -like 'a*'}}

Similarly you can pass the same sort of command block to Invoke-Expression cmdlet, and you waill get the same results.
Invoke-Expression 'Get-Process | Where-Object { $_.Name -like "a*"}'

Just remember to put code after Invoke-Expression in single quotation marks. If you use double quotation marks, PowerShell will replace all the variable names in the string with the variable contents.

A scriptblock can also uses the param statement to define a parameter. You could easily define your own anonymous scriptblock with arguments. The following scriptblock accepts two parameters and multiplies them:
{ param($value1, $value2) $value1 * $value2 }

To invoke the scriptblock, use the call operator:
& { param($value1, $value2) $value1 * $value2 } 10 5

No comments:

Post a Comment