- Courses
- đź’»Programming Languages
- 🪟PowerShell
- PowerShell for System Administration
- Remote Management
- Invoke-Command
On this page
PowerShell Invoke-Command – Remote and Local Command Execution
Updated on June 18, 2026
By Enrico Hochkoeppler
Web Developer & TutoriaLibre Founder
Invoke-Command is the central cmdlet for running PowerShell code on one or more computers — remote or local. It sends a script block or script file to the target, executes it there, serializes the results, and returns them to your local session as PowerShell objects you can continue to work with. A single Invoke-Command call can target dozens of computers simultaneously. It supports WinRM-based connections on Windows, SSH-based connections across Windows, Linux, and macOS, persistent PSSessions for multi-step workflows, and background job execution with -AsJob.
How Invoke-Command Works​
When you run a command locally, PowerShell executes it in your current session with access to your local variables, modules, and file system. When you use Invoke-Command against a remote computer, a fundamentally different process occurs:
- PowerShell establishes a connection to the target computer using WinRM (Windows) or SSH (cross-platform)
- A temporary PowerShell session is created on the remote machine
- The script block or script file executes entirely on the remote system — not on your machine
- The results are serialized (converted to XML) and transmitted back to your local session
- PowerShell deserializes them into local objects you can pipe, sort, and filter
Understanding step 4 and 5 is critical. The objects you receive back are deserialized copies — snapshots of what existed remotely. They retain their properties but lose their methods. You cannot call .Kill() on a Process object returned from a remote session the way you could on a locally-created one. This distinction affects how you structure remote operations.
Running a Command on a Single Remote Computer​
The simplest Invoke-Command call uses -ComputerName and -ScriptBlock:
Invoke-Command -ComputerName "Server01" -ScriptBlock {
Get-Service
}
Get-Service runs on Server01, not on your local machine. The list of services returned reflects the remote system's configuration. The results come back as deserialized ServiceController-like objects with all their properties intact.
Running Commands on Multiple Computers Simultaneously​
-ComputerName accepts a comma-separated list or an array. PowerShell runs the script block on all targets in parallel (up to the throttle limit):
Invoke-Command -ComputerName "Server01", "Server02", "Server03" -ScriptBlock {
Get-Process | Where-Object WorkingSet64 -gt 100MB
}
Each target gets its own session, runs the script block independently, and returns results. All results are merged into a single output stream with a PSComputerName property on each object indicating which machine produced it.
To load computer names from a file:
$servers = Get-Content "C:\Admin\servers.txt"
Invoke-Command -ComputerName $servers -ScriptBlock {
Get-WinEvent -LogName System -Newest 10
}
Get-Content reads each line of the file as a string. The resulting array is passed directly to -ComputerName. This pattern scales to hundreds of servers with one command.
To identify results by source computer, access the PSComputerName property:
Invoke-Command -ComputerName "Server01", "Server02" -ScriptBlock {
Get-Service -Name "Spooler"
} | Select-Object PSComputerName, Name, Status
PSComputerName is automatically added to every object returned from a remote session. Selecting it alongside the object's own properties lets you build cross-environment comparison reports.
The Remote Execution Context​
A script block running remotely executes in the remote machine's environment. Several implications follow from this:
- File paths like
C:\Windowsrefer to the remote file system - Environment variables (
$env:COMPUTERNAME,$env:USERNAME) reflect the remote machine's values - Installed modules and available commands depend on what is on the remote host
- Local variables from your session are not automatically available in the remote script block
- The current directory on the remote machine is the PowerShell default (
$HOMEor$env:USERPROFILE)
This isolation is intentional. It ensures remote execution is predictable and does not accidentally pick up local state. It also means you must explicitly transmit any local data that the remote script needs.
Passing Local Variables with $using:​
To reference a local variable inside a remote script block, use the $using: scope modifier. It captures the value of the variable at call time and transmits it to the remote session:
$serviceName = "Spooler"
$thresholdMB = 200
Invoke-Command -ComputerName "Server01" -ScriptBlock {
$svc = Get-Service -Name $using:serviceName
"Service '$($svc.DisplayName)' is $($svc.Status)"
Get-Process | Where-Object { $_.WorkingSet64 -gt ($using:thresholdMB * 1MB) } |
Select-Object Name, Id
}
$using:serviceName transmits the local value "Spooler" into the remote session. $using:thresholdMB transmits 200. The remote script block cannot modify the originals — $using: is read-only in the remote context. If you need bidirectional data exchange, use a PSSession with multiple sequential Invoke-Command calls.
Passing Arguments with -ArgumentList​
An alternative to $using: is the -ArgumentList parameter, which passes values positionally and maps them to $args or to param() variables inside the script block:
# Using $args (positional, no param block needed)
Invoke-Command -ComputerName "Server01" -ScriptBlock {
Get-Service -Name $args[0]
} -ArgumentList "Spooler"
$args[0] receives the first argument. Multiple arguments are accessed as $args[1], $args[2], and so on. This approach is concise but relies on order, which makes the code harder to read when there are many arguments.
The param() keyword inside the script block names the arguments explicitly and is the cleaner approach:
Invoke-Command -ComputerName "Server01", "Server02" -ScriptBlock {
param(
[string]$ServiceName,
[int]$ThresholdMB
)
$svc = Get-Service -Name $ServiceName
"Status of $ServiceName on $env:COMPUTERNAME : $($svc.Status)"
Get-Process |
Where-Object { $_.WorkingSet64 -gt ($ThresholdMB * 1MB) } |
Select-Object Name, Id, @{ n="MemMB"; e={ [math]::Round($_.WorkingSet64/1MB,1) } }
} -ArgumentList "Spooler", 150
-ArgumentList "Spooler", 150 maps "Spooler" to $ServiceName and 150 to $ThresholdMB via the param() block in order. This makes the remote script block self-documenting and avoids relying on index positions.
Running a Script File Remotely with -FilePath​
Instead of inline script blocks, Invoke-Command can send an entire .ps1 script file to run on remote computers:
Invoke-Command -ComputerName "Server01", "Server02" -FilePath "C:\Scripts\Cleanup.ps1"
When -FilePath is used:
- The script file is read from the local computer
- Its contents are transmitted to each remote computer
- The script executes on the remote system
- Results are returned to the local session
The script file does not need to exist on the remote computers — it is read locally and sent over the connection. This makes it straightforward to deploy and run maintenance scripts across a fleet of servers from a single management workstation.
Using Credentials​
When your current credentials cannot authenticate to the remote computer — different domain, workgroup machine, or elevated account required — supply credentials with -Credential:
$cred = Get-Credential
Invoke-Command -ComputerName "Server01" -Credential $cred -ScriptBlock {
hostname
whoami
}
Get-Credential prompts for a username and password and returns a PSCredential object. The credential is used to authenticate the remote session. For automation scripts where interactive prompting is not acceptable, create the credential programmatically:
$password = ConvertTo-SecureString "P@ssw0rd!" -AsPlainText -Force
$cred = [PSCredential]::new("DOMAIN\AdminUser", $password)
Invoke-Command -ComputerName "Server01" -Credential $cred -ScriptBlock {
Get-Service -Name "Spooler"
}
ConvertTo-SecureString -AsPlainText -Force converts a plaintext string to a SecureString. In production, read the password from a secrets manager or from an encrypted credential file rather than embedding it in the script.
Temporary Sessions vs Persistent PSSessions​
Temporary sessions (default -ComputerName behaviour)​
When -ComputerName is used without a pre-existing session, Invoke-Command creates a new session for the command and destroys it when the command completes. This means each call starts fresh:
# First call — creates a session, runs command, destroys session
Invoke-Command -ComputerName "Server01" -ScriptBlock {
$p = Get-Process powershell
}
# Second call — creates a NEW session. $p from the first call is gone.
Invoke-Command -ComputerName "Server01" -ScriptBlock {
$p.VirtualMemorySize # ERROR — $p does not exist in this new session
}
Each -ComputerName call creates an isolated execution environment. Variables, loaded modules, and working directories do not persist between calls.
Persistent PSSessions for multi-step workflows​
When a series of commands must share state — the same variables, the same loaded module, the same accumulated data — create a persistent session with New-PSSession and pass it to -Session:
# Create a persistent session
$session = New-PSSession -ComputerName "Server01"
# First command — $p is set in the persistent session
Invoke-Command -Session $session -ScriptBlock {
$p = Get-Process powershell
}
# Second command — $p still exists because it is the same session
Invoke-Command -Session $session -ScriptBlock {
"PowerShell is using $([math]::Round($p.WorkingSet64 / 1MB, 1)) MB"
}
# Clean up the session when done
Remove-PSSession -Session $session
$p persists across the two Invoke-Command calls because both target the same PSSession. This is essential for workflows where the first command prepares data that subsequent commands consume.
Always close persistent sessions when they are no longer needed with Remove-PSSession. Orphaned sessions consume resources on both the local and remote computers.
Running as a Background Job with -AsJob​
-AsJob submits the remote command as a background job. The Invoke-Command call returns immediately with a Job object, and the remote command runs in the background:
$job = Invoke-Command -ComputerName "Server01", "Server02" -ScriptBlock {
Get-WinEvent -LogName Application -Newest 100
} -AsJob -JobName "CollectEventLogs"
"Job started — do other work here"
# Wait for the job to finish and collect results
Receive-Job -Job $job -Wait -AutoRemoveJob
-AsJob is useful when the remote operation is long-running and you do not want to block the current session. Receive-Job -Wait blocks until the job completes and retrieves the results. -AutoRemoveJob removes the job object from the job store after results are collected.
Check job status without blocking:
$job = Invoke-Command -ComputerName $servers -ScriptBlock { Start-Sleep 10; "Done" } -AsJob
$job.State # Running, Completed, Failed, etc.
Receive-Job -Job $job # retrieves results without waiting if the job is still running
SSH-Based Remoting (Cross-Platform)​
Starting with PowerShell 6.0, Invoke-Command supports SSH as a transport layer alongside WinRM. SSH-based remoting works on Windows, Linux, and macOS — making it the cross-platform alternative to WinRM for heterogeneous environments.
SSH remoting requires:
- SSH installed on the local machine
- SSH configured on the remote machine with a PowerShell SSH endpoint (typically in
sshd_config)
Connecting with a hostname​
Invoke-Command -HostName "ubuntu-server-01" -UserName "admin" -ScriptBlock {
uname -a
Get-Process | Select-Object -First 5
}
-HostName specifies the remote computer. -UserName provides the SSH username. PowerShell prompts for the password if no key-based authentication is configured.
Connecting with a key file​
Invoke-Command -HostName "ubuntu-server-01" -UserName "admin" -KeyFilePath "~/.ssh/id_rsa" -ScriptBlock {
Get-Service | Select-Object Name, Status
}
-KeyFilePath provides the path to the SSH private key for passwordless authentication. This is the recommended approach for automation.
Connecting to multiple machines with SSHConnection​
The -SSHConnection parameter accepts an array of hashtables, each describing one connection:
$connections = @(
@{ HostName = "win-server-01"; UserName = "Administrator"; KeyFilePath = "~/.ssh/id_rsa" }
@{ HostName = "ubuntu-01"; UserName = "admin"; KeyFilePath = "~/.ssh/id_rsa" }
@{ HostName = "macos-01"; UserName = "user"; KeyFilePath = "~/.ssh/id_rsa" }
)
Invoke-Command -SSHConnection $connections -ScriptBlock {
"$env:COMPUTERNAME running PowerShell $($PSVersionTable.PSVersion)"
}
Each hashtable describes one target. The same script block runs on all three platforms simultaneously. The results include PSComputerName so you can distinguish which machine produced each line.
Controlling Concurrency with -ThrottleLimit​
When -ComputerName targets many machines, PowerShell runs commands in parallel. -ThrottleLimit controls the maximum number of simultaneous connections (default: 32):
$servers = Get-Content "C:\Admin\all-servers.txt" # 200 servers
Invoke-Command -ComputerName $servers -ThrottleLimit 50 -ScriptBlock {
Get-Service | Where-Object Status -eq Stopped
}
-ThrottleLimit 50 allows up to 50 concurrent connections. The remaining servers queue and are processed as slots free up. Setting this too high can overwhelm the network or the WinRM listener on heavily loaded targets. Setting it too low increases total runtime. Tune it based on network capacity and target server load.
Running Locally with Invoke-Command​
Invoke-Command can also execute a script block on the local computer. When called with just -ScriptBlock and no computer name, it runs the block in a child scope of the current session:
Invoke-Command -ScriptBlock {
"Running locally. Computer: $env:COMPUTERNAME"
Get-Process | Select-Object -First 3
}
This is useful for testing script blocks that will later be deployed remotely — you can verify logic locally before sending it to remote machines. The child scope means local variables set inside the block are not accessible outside it (unlike dot-sourcing).
Including localhost in a -ComputerName list runs the script block on the local machine through WinRM along with the remote targets:
Invoke-Command -ComputerName "Server01", "Server02", "localhost" -ScriptBlock {
Get-WinEvent -LogName System -Newest 5
}
Understanding Serialized Objects​
Every object returned by Invoke-Command from a remote session is a deserialized copy. PowerShell converts the original .NET object to XML (serialization) for transmission, then rebuilds it locally from that XML (deserialization).
The deserialized copy:
- Retains all properties — you can access
.Name,.Status,.Id, and any other property - Loses all methods — you cannot call
.Stop(),.Kill(),.Start(), or any method - Has a different type name — a
ServiceControllerbecomesDeserialized.System.ServiceProcess.ServiceController
Practical consequences:
# Returns a deserialized ServiceController — properties work, methods do not
$remoteSvc = Invoke-Command -ComputerName "Server01" -ScriptBlock {
Get-Service -Name "Spooler"
}
$remoteSvc.Status # Works — returns 'Running'
$remoteSvc.Stop() # Fails — method not available on deserialized object
The correct pattern is to perform the action inside the remote script block while you still have access to the live object:
# Perform the action remotely, where the live object is available
Invoke-Command -ComputerName "Server01" -ScriptBlock {
Get-Service -Name "Spooler" | Stop-Service
}
For simple types — strings, integers, booleans, arrays, hashtables — serialization and deserialization are transparent. Only complex .NET objects with methods are affected.
Practical Administrative Patterns​
Check disk space across a server fleet​
$servers = Get-Content "C:\Admin\servers.txt"
Invoke-Command -ComputerName $servers -ScriptBlock {
Get-PSDrive -PSProvider FileSystem | Select-Object Name, Root,
@{ n="FreeGB"; e={ [math]::Round($_.Free / 1GB, 2) } },
@{ n="TotalGB"; e={ [math]::Round(($_.Used + $_.Free) / 1GB, 2) } }
} | Select-Object PSComputerName, Name, Root, FreeGB, TotalGB |
Sort-Object PSComputerName, Name |
Format-Table -AutoSize
The results from all servers are merged and sorted by computer name and drive letter. PSComputerName in the Select-Object call ensures the source is visible in the table.
Restart a service on multiple servers​
$targetServers = "Server01", "Server02", "Server03"
$targetService = "Spooler"
Invoke-Command -ComputerName $targetServers -ScriptBlock {
param([string]$SvcName)
Restart-Service -Name $SvcName -Force
$svc = Get-Service -Name $SvcName
[PSCustomObject]@{
ComputerName = $env:COMPUTERNAME
Service = $SvcName
Status = $svc.Status
}
} -ArgumentList $targetService
-ArgumentList $targetService passes "Spooler" to the $SvcName parameter in the remote param() block. Each server restarts the service and returns a custom object with the resulting status. The env:COMPUTERNAME inside the script block refers to the remote machine's name.
Collect event logs and export to a central file​
$cred = Get-Credential "DOMAIN\Admin"
$servers = "DC01", "DC02", "WebServer01"
$events = Invoke-Command -ComputerName $servers -Credential $cred -ScriptBlock {
Get-WinEvent -LogName Application -MaxEvents 50 |
Where-Object { $_.LevelDisplayName -eq "Error" }
}
$events |
Select-Object PSComputerName, TimeCreated, Id, Message |
Sort-Object PSComputerName, TimeCreated |
Export-Csv "C:\Reports\remote_errors.csv" -NoTypeInformation
The events from all three servers merge into $events. The pipeline then sorts and exports them to a single CSV file with PSComputerName as the first column so the source server is clear in the report.
Key Parameters Reference​
ParameterPurpose-ComputerNameTarget one or more computers by name-ScriptBlockThe code to execute on the target-FilePathPath to a local .ps1 file to run remotely-SessionA persistent PSSession to run inside-CredentialAlternate credentials for authentication-ArgumentListArguments passed to the script block via $args or param()``-AsJobRun as a background job; return immediately-ThrottleLimitMaximum simultaneous connections (default 32)-InDisconnectedSessionRun in a session that disconnects from the caller-HostNameTarget for SSH-based remoting-UserNameSSH username-KeyFilePathSSH private key path for passwordless auth-SSHConnectionArray of hashtables for multi-target SSH connections-HideComputerNameSuppress the PSComputerName property on output objects-ConfigurationNameConnect to a specific PowerShell session configuration
Common Mistakes to Avoid​
Expecting local variables to be available in the remote script block. Local variables are not transmitted automatically. Use $using:variableName or -ArgumentList with param() to pass values into the remote script block.
Trying to call methods on objects returned from remote sessions. Returned objects are deserialized and have no methods. Perform actions (stopping services, killing processes) inside the remote script block where the live object is available.
Using -ComputerName for multi-step workflows that share state. Each -ComputerName call creates a fresh session. Variables set in one call do not exist in the next. Use New-PSSession with -Session for stateful workflows.
Not closing PSSessions. Each open PSSession consumes resources on both machines. Always call Remove-PSSession when a persistent session is no longer needed.
Setting -ThrottleLimit too high. Targeting 500 servers with -ThrottleLimit 500 opens 500 simultaneous WinRM connections. This can overwhelm network infrastructure and target servers. Start with the default of 32 and increase gradually based on observed performance.
Forgetting to add PSComputerName to output when targeting multiple machines. Results from many computers merge into one stream. Without PSComputerName in the output, it is impossible to determine which computer produced each result.
Found this helpful? Share the knowledge...
... or support this project to keep it alive!
Previous
PowerShell Remoting (WinRM)
Next
Sessions and Session Configuration
-
How
Invoke-CommandWorks -
Running a Command on a Single Remote Computer
-
Running Commands on Multiple Computers Simultaneously
-
The Remote Execution Context
-
Passing Local Variables with
$using: -
Passing Arguments with
-ArgumentList -
Running a Script File Remotely with
-FilePath -
Using Credentials
-
Temporary Sessions vs Persistent PSSessions
- Temporary sessions (default
-ComputerNamebehaviour) - Persistent PSSessions for multi-step workflows
- Temporary sessions (default
-
Running as a Background Job with
-AsJob -
SSH-Based Remoting (Cross-Platform)
- Connecting with a hostname
- Connecting with a key file
- Connecting to multiple machines with
SSHConnection
-
Controlling Concurrency with
-ThrottleLimit -
Running Locally with
Invoke-Command -
Understanding Serialized Objects
-
Practical Administrative Patterns
- Check disk space across a server fleet
- Restart a service on multiple servers
- Collect event logs and export to a central file
-
Key Parameters Reference
-
Common Mistakes to Avoid
