How scriptblock works in PowerShell?

PowerShellMicrosoft TechnologiesSoftware & Coding

Scriptblock is a set of commands which can be executed together when they are invoked. In PowerShell, generally, we write individual commands. Scriptblock can be written with two curly brackets.

Example

$sb = {Get-Process powershell; Get-Service W32Time}

Here we have written two commands under scriptblock. If you directly run this command, scriptblock treats them as a string.

PS C:\> $sb
Get-Process powershell; Get-Service W32Time

To run the commands inside the scritblock, use Invoke-Command with the -Scriptblock parameter.

Invoke-Command -ScriptBlock $sb

Output

Handles NPM(K)    PM(K)    WS(K)    CPU(s)    Id    SI    ProcessName
------- ------    -----    -----    ------    --    --    -----------
529       44    240240    256164    36.02    7668    1    powershell
Status : Running
Name   : W32Time
DisplayName : Windows Time

To run the commands on the remote computers, use -ComputerName parameter.

Example

Invoke-Command -ComputerName Test1-Win2k16,Test1-Win2k12 -ScriptBlock $sb

Output

PS C:\Scripts\AppdInstallation_Remote> Invoke-Command -ComputerName Test1-
Win2k16,Test1-Win2k12 -ScriptBlock $sb
Handles    NPM(K)    PM(K)    WS(K)    CPU(s)    Id    SI P   rocessName
PSComputerName
------- -   -----    -----    -----    ------    --    --    -----------
--------------
434          29     46200    47564    0.70     3228   1    powershell
Test1-Win2k12
Status          : Running
Name            : Spooler
DisplayName     : Print Spooler
PSComputerName  : Test1-Win2k12
583    29    57892    64636    0.59    4524    1    powershell    Test1-Win2k16
Status         : Stopped
Name           : Spooler
DisplayName    : Print Spooler
PSComputerName : Test1-Win2k16

You can also pass the parameters inside the scriptblock using -ArgumentList parameter in InvokeCommand cmdlet. Declaration of param will be the same as the function in PowerShell.

Example

Invoke-Command -ComputerName Test1-Win2k16,Test1-Win2k12 -ScriptBlock $sb
$sb = {
   param($process,$service)
   Get-Process -Name $process
   Get-Service -Name $service
}
Invoke-Command -ScriptBlock $sb -ArgumentList "PowerShell","W32Time"

Output

NPM(K)    PM(M)    WS(M)    CPU(s)    Id    SI    ProcessName
------    -----    -----    ------    --    --    -----------
43       234.39    22.84    43.61    7668    1    powershell
Status       : Running
Name         : W32Time
DisplayName  : Windows Time
raja
Published on 03-Sep-2020 14:22:38
Advertisements