PowerShell Invoke-Command
Invoke-Command is a command that runs a block of code for you. In this lesson it runs the block on the local machine.
Run a block locally
Invoke-Command runs the block and prints its result. No computer name is given, so it runs here.
Invoke-Command -ScriptBlock { "Hello from a block" }Pass a value into a block
ArgumentList passes a value into the block. The block param names that value.
Invoke-Command -ScriptBlock { param($Name) "Hello, $Name" } -ArgumentList "Ana"Run several blocks in order
Each block runs in turn, and its result is saved. Printing the saved results shows them in order.
$first = Invoke-Command -ScriptBlock { 10 + 5 }
$second = Invoke-Command -ScriptBlock { 20 + 5 }
$third = Invoke-Command -ScriptBlock { 30 + 5 }
"$first, $second, $third"Example
$first = Invoke-Command -ScriptBlock { param($Name) "Hello, $Name" } -ArgumentList "Ana"
$second = Invoke-Command -ScriptBlock { 10 + 20 }
"$first, total is $second"Key points
- Invoke-Command: the command that runs a script block.
- Script block: a bundle of code wrapped in braces.
- -ScriptBlock: the flag that holds the code to run.
- -ArgumentList: the flag that passes values into the block, in order.
- Block param: the list inside the block that names the values it receives.
- Local run: this lesson runs every block on the local machine only.
In this example, the first block greets Ana with a passed value, the second block adds two numbers, and the saved results print together in order.
Note
Real remoting to another computer needs a configured host, so no remote host is contacted here.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
Which flag passes a local value into a script block?