Remoting & Automation
Run commands across many machines with PowerShell remoting and background jobs.
Theory
PowerShell remoting runs commands on remote machines, over WinRM on Windows or SSH cross-platform. Two patterns:
Invoke-Command— run a script block on one or many computers at once (fan-out), returning objects with the source machine attachedEnter-PSSession— an interactive session on a single remote host
For long or parallel work, use jobs (Start-Job, -AsJob) or
ForEach-Object -Parallel. Because results come back as objects, you can pipe and
aggregate them as if they ran locally.
Real-World Example
# Run on many servers at once
Invoke-Command -ComputerName web1, web2, web3 -ScriptBlock {
Get-Service -Name 'w3svc' | Select-Object Status
}
# Interactive remote session
Enter-PSSession -ComputerName db1
# ... run commands as if local ...
Exit-PSSession
# Parallel local work
1..5 | ForEach-Object -Parallel { "Item $_"; Start-Sleep 1 } -ThrottleLimit 5 Hands-On Exercise
- Use
Invoke-Commandto query a service’s status on multiple hosts (or localhost). - Note how
PSComputerNameidentifies which machine each result came from. - Run a slow task as a background job with
Start-Joband retrieve it withReceive-Job. - Compare
Invoke-Command(fan-out) vsEnter-PSSession(interactive) use cases.
Cheat Sheet▾
| Task | Command |
|---|---|
| Run remotely (fan-out) | Invoke-Command -ComputerName … -ScriptBlock {…} |
| Interactive session | Enter-PSSession -ComputerName host |
| Persistent session | New-PSSession |
| Background job | Start-Job / Receive-Job |
| Parallel loop | ForEach-Object -Parallel {…} |
| Source of result | $_.PSComputerName |
Common Interview Questions▾
What's the difference between Invoke-Command and Enter-PSSession?
Invoke-Command runs a script block on one or many machines (fan-out) and returns objects. Enter-PSSession opens an interactive shell on a single remote host.
How does remoting return data from many machines?
As objects tagged with PSComputerName, so you can pipe, filter, and aggregate results from the whole fleet just like local output.
Official Documentation
📝 My notes on this topic
Auto-saves as you type