Remoting & Automation

💤0
Lv 10 XP
← ⚙️ Scripting & Automation · PowerShell

Remoting & Automation

Advanced ⭐ 120 XP ⏱ 16 min #powershell#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 attached
  • Enter-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
  1. Use Invoke-Command to query a service’s status on multiple hosts (or localhost).
  2. Note how PSComputerName identifies which machine each result came from.
  3. Run a slow task as a background job with Start-Job and retrieve it with Receive-Job.
  4. Compare Invoke-Command (fan-out) vs Enter-PSSession (interactive) use cases.
🧾Cheat Sheet
TaskCommand
Run remotely (fan-out)Invoke-Command -ComputerName … -ScriptBlock {…}
Interactive sessionEnter-PSSession -ComputerName host
Persistent sessionNew-PSSession
Background jobStart-Job / Receive-Job
Parallel loopForEach-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