CodeSteps

Python, C, C++, C#, PowerShell, Android, Visual C++, Java ...

PowerShell – Script blocks and Invoke-Command

In our previous articles, we have discussed PowerShell Scripts and PowerShell Functions. PowerShell provides Script blocks also to group the commands and invoke them when required. In this article, we will discuss PowerShell Script blocks.

Script block in PowerShell

Script blocks are the group of related PowerShell commands and will be executed on demand. Script blocks DO NOT have names. If we the name to the script block; we can call it a function.

Defining a Script block

The commands in Script blocks are grouped inside the curly braces (“{ and }”). A script block can take arguments and also can return the results as a single object or an array of objects.

Here is a sample script block:

PS C:\PowerShell> {
>> Write-Output "First Line"
>> Write-Output "Second Line"
>> }
>>

Write-Output "First Line"
Write-Output "Second Line"

PS C:\PowerShell>

Invoking a Script block

As Script blocks do not have names; we can not invoke them like functions. PowerShell provides a special command Invoke-Command to invoke the script blocks.

Invoke-Command has a parameter -Scriptblock through which we can pass our script block to invoke. Above script block, we run through Invoke-Command like below:

PS C:\PowerShell> Invoke-Command -Scriptblock {
>> Write-Output "First Line"
>> Write-Output "Second Line"
>> }
>>
First Line
Second Line
PS C:\PowerShell>

Passing arguments to a Script block

We can also define arguments for the Script block. These can be defined using param statement. param statement should be the first statement in the script block. In functions, we can define parameters outside of the block; whereas, in the script block, parameters are defined inside the block ONLY.

To pass the parameters, Invoke-Command has a property -Argumentlist which allows passing parameters to the script block; and the parameters should be separated by a comma (“,”). Here is an example script block contains parameters; and the script block is invoked using Invoke-Command by passing arguments to it:

PS C:\PowerShell> Invoke-Command -Scriptblock {
>> param($One, $Two)
>> $One
>> $Two
>> } -Argumentlist "Hello!", "How are you?"
>>
Hello!
How are you?
PS C:\PowerShell>

We will discuss more topics as we go.

[..] David

PowerShell – Script blocks and Invoke-Command

Leave a Reply

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

Scroll to top