Invoke-Command¶
Invoke-Command is the central cmdlet used to execute PowerShell code on one or more remote computers. While PowerShell Remoting provides the communication channel (via WinRM), Invoke-Command is the mechanism that sends instructions across that channel and retrieves the results. It allows you to run script blocks, entire scripts, or commands remotely, while still receiving structured PowerShell objects locally.
This section explains how Invoke-Command works, how to use it effectively, and how to reason about its behavior in real administrative scenarios.
1. The Purpose of Invoke-Command¶
When you run a command locally, PowerShell executes it within your current session.
When you use Invoke-Command, PowerShell:
- Establishes a connection to the remote machine (or machines).
- Creates a temporary PowerShell session on each target.
- Executes the script block on the remote system, not on your machine.
- Serializes the results and sends them back to your local session.
- Returns the results as PowerShell objects that you can continue to process locally.
This model allows you to manage remote systems with the same commands you already know, without needing to log in interactively.
2. Executing a Script Block Remotely¶
The most common usage of Invoke-Command is to run a script block on a remote computer.
Example: retrieving services from a remote machine¶
Invoke-Command -ComputerName "SERVER01" -ScriptBlock {
Get-Service
}
In this example:
- The
Get-Servicecommand runs on SERVER01, not on your local machine. - The output is returned as service objects, which you can sort, filter, or pipe into other commands locally.
- The remote environment determines the results: for example, the list of services reflects the remote system’s configuration.
This is the simplest and most direct form of remote execution.
3. Executing Commands on Multiple Machines¶
Invoke-Command accepts multiple computer names, allowing you to run the same script block across many systems simultaneously.
Example: checking PowerShell processes on several servers¶
Invoke-Command -ComputerName "SERVER01","SERVER02" -ScriptBlock {
Get-Process -Name "powershell"
}
Here, the script block is executed independently on each machine.
The results are combined into a single output stream, but each object includes metadata indicating which computer produced it. This makes it possible to analyze results across an entire environment.
4. Understanding the Remote Execution Context¶
When a script block runs remotely, it executes in the remote machine’s environment, not your own. This has several important implications:
- File paths such as
C:\Windowsrefer to the remote system. - Environment variables reflect the remote machine’s configuration.
- Installed modules and available commands depend on the remote host.
- Local variables are not automatically available inside the remote script block.
This separation ensures that remote execution is predictable and isolated, but it also means you must explicitly pass local values when needed.
5. Passing Local Variables to Remote Commands¶
To use a local variable inside a remote script block, PowerShell provides the $using: scope modifier.
Example: passing a local variable¶
$serviceName = "Spooler"
Invoke-Command -ComputerName "SERVER01" -ScriptBlock {
Get-Service -Name $using:serviceName
}
In this example:
$serviceNameis defined locally.$using:serviceNameinstructs PowerShell to transmit its value to the remote session.- The remote machine receives the value
"Spooler"and uses it in theGet-Servicecommand.
This mechanism is essential when writing dynamic or parameterized remote scripts.
6. Running Script Files Remotely¶
Invoke-Command can also execute an entire .ps1 script on a remote machine.
Example: running a script file¶
Invoke-Command -ComputerName "SERVER01" -FilePath "C:\Scripts\Cleanup.ps1"
In this case:
- The script file is read locally.
- Its contents are transmitted to the remote machine.
- The script executes entirely on the remote system.
- The results are returned to your local session.
This is a common technique for deploying administrative tasks across multiple servers.
7. Using Credentials with Invoke-Command¶
In many environments, your current credentials may not be sufficient to access a remote machine.
Invoke-Command allows you to specify alternate credentials.
Example: prompting for credentials¶
$cred = Get-Credential
Invoke-Command -ComputerName "SERVER01" -Credential $cred -ScriptBlock {
hostname
}
Here:
Get-Credentialprompts you for a username and password.- The credentials are used to authenticate the remote session.
- The command
hostnameruns on the remote machine and returns its computer name.
This is essential when managing systems across different domains or security boundaries.
8. Using Invoke-Command with PSSessions¶
Although Invoke-Command can create temporary sessions automatically, it can also operate on persistent sessions created with New-PSSession.
Example: using a persistent session¶
$session = New-PSSession -ComputerName "SERVER01"
Invoke-Command -Session $session -ScriptBlock {
Get-Date
}
A persistent session maintains state between commands, allowing you to:
- Store variables
- Load modules
- Maintain a working directory
- Execute multi‑step workflows
This is particularly useful for complex administrative tasks.
9. Practical Administrative Examples¶
Checking disk space on multiple servers¶
Invoke-Command -ComputerName (Get-Content "servers.txt") -ScriptBlock {
Get-PSDrive -PSProvider FileSystem
}
Restarting a remote service¶
Invoke-Command -ComputerName "SERVER01" -ScriptBlock {
Restart-Service -Name "Spooler"
}
Gathering event logs from remote machines¶
Invoke-Command -ComputerName "SERVER01" -ScriptBlock {
Get-EventLog -LogName System -Newest 20
}
Each of these examples demonstrates how Invoke-Command allows you to centralize administrative tasks and operate across multiple systems efficiently.
10. Summary¶
Invoke-Command is the primary tool for executing PowerShell code remotely. It provides:
- A consistent way to run commands on one or many remote systems.
- A clear separation between local and remote execution environments.
- The ability to pass local variables into remote script blocks.
- Support for running entire script files remotely.
- Integration with persistent PSSessions for multi‑step workflows.
- Full access to structured PowerShell objects returned from remote hosts.
Mastering Invoke-Command is essential for effective remote administration and forms the basis for large‑scale automation in Windows environments.