Search notes:

PowerShell cmdLet Invoke-Command

The PowerShell cmdlet invoke-command is typically used to execute a script block (-scriptBlock …) or a PowerShell script file (-filePath …).
Use invoke-expression to execute a command (including arguments) whose text is stored in a variable.

Call a script block

The following example assigns a script block to a variable and then uses the invoke-command cmdLet to execute it:
$sb = {
  write-output 'Hello from a script block'
}
write-output 'Going to invoke command with script block:'
invoke-command $sb
Github repository about-PowerShell, path: /cmdlets/command/invoke/script-block.ps1

Passing arguments to a script block

The -argumentList parameter of invoke-command allows to pass parameters to a script block. Note, that the values of the parameters need to be separated by commas in the invocation:
$sb = {
  param($param_1, $param_2)
  write-output "param_1 = $param_1"
  write-output "param_2 = $param_2"
}

invoke-command -scriptBlock $sb -argumentList 42, 'Hello World'
Github repository about-PowerShell, path: /cmdlets/command/invoke/argumentList.ps1

Execute commands/scripts on a remote machine

Command

Using the -computerName parameter, it is possible to run a command on a remote computer.
In order to run the command, PowerShell establishes a temporary connection. As soon as the command has finished, the connection is closed. Thus, variables, functions etc. that were defined in the command, will be lost.
In order to prevent such a loss, a PsSession (which is basically a persistent connection) should be created.

Script

A PowerShell script file can be executed on a remote machine using the -filePath command option.

Running commands in multiple PsSessions

It is possible to run a command in mutliple PsSessions:
#    Create three sessions to the servers
#    named alpha, beta and gamma:
#
$ses = new-psSession -computerName alpha, beta, gamma

#    Run a command (or more accurately: a script block) all three servers:
#
invoke-command -session $ses -scriptBlock { … }

See also

invoke-command is one of the cmdLets with the -computerName and -asJob parameter.
The command parameter -credential.
Powershell command noun: command

Index