Learn › PowerShell

PowerShell Remoting: Run Commands on Many Servers with Invoke-Command

PowerShell remoting: enable WinRM, use Enter-PSSession and Invoke-Command on many servers, pass variables, throttle jobs and handle credentials.

Intermediate 11 min read
By Gopinath Karthikeyan

Logging in to servers one by one with RDP doesn’t scale. PowerShell remoting lets you run the same command on one server or two hundred – in parallel – and get the results back as objects on your own machine.

How it works

Remoting uses WinRM (Windows Remote Management) on TCP 5985 (HTTP, traffic still encrypted with Kerberos in a domain) or 5986 (HTTPS). It’s enabled by default on Windows Server 2012 and later. In a domain, Kerberos handles authentication with your current account.

Check or enable it on a server:

Test-WSMan SRV01                 # from your machine – does WinRM answer?
Enable-PSRemoting -Force         # on the server, as admin, if needed
PowerShell remoting with Invoke-Command across many servers over WinRM Your admin PC Invoke-Command -ComputerName … உங்கள் admin PC Invoke-Command -ComputerName … WinRM 5985/5986 · 32 at a time WinRM 5985/5986 · ஒரே நேரத்தில் 32 SRV01 Runs thescript block SRV01 Script blockஇயங்கும் SRV02 Runs thescript block SRV02 Script blockஇயங்கும் SRV03 Runs thescript block SRV03 Script blockஇயங்கும் Objects come back Each tagged with PSComputerName Objects திரும்ப வரும் ஒவ்வொன்றிலும் PSComputerName Double hop: SRV01 can’t passyour credentials on to a file share Double hop: உங்கள் credentials-ஐ SRV01file share-க்கு அனுப்ப முடியாது
Invoke-Command sends the script block to many servers over WinRM in parallel and returns objects tagged with PSComputerName.Invoke-Command script block-ஐ WinRM மூலம் பல servers-க்கு ஒரே நேரத்தில் அனுப்பி, PSComputerName உடன் objects-ஐ திருப்பித் தருகிறது.

Interactive: Enter-PSSession

Like SSH for Windows – one server, interactive:

Enter-PSSession -ComputerName SRV01
[SRV01]: PS C:\> Get-Service W3SVC
[SRV01]: PS C:\> Exit-PSSession

One-to-many: Invoke-Command

$servers = Get-Content C:\Temp\servers.txt

Invoke-Command -ComputerName $servers -ScriptBlock {
    Get-CimInstance Win32_OperatingSystem |
        Select-Object @{n='UptimeDays';e={[math]::Round(((Get-Date) - $_.LastBootUpTime).TotalDays,1)}}
} | Select-Object PSComputerName, UptimeDays | Sort-Object UptimeDays -Descending

PowerShell runs on up to 32 servers at a time by default (-ThrottleLimit changes that) and adds a PSComputerName property so you know which result came from where.

Passing local values: $using:

The script block runs on the remote server, so your local variables don’t exist there. Use $using::

$serviceName = 'Spooler'
Invoke-Command -ComputerName $servers -ScriptBlock {
    Get-Service -Name $using:serviceName
}

Or pass arguments:

Invoke-Command -ComputerName $servers -ScriptBlock { param($n) Get-Service $n } -ArgumentList 'Spooler'

Run a local script file remotely

Invoke-Command -ComputerName $servers -FilePath C:\Scripts\Get-DiskReport.ps1

The script is copied over the session – no need to put it on each server.

Sessions for several commands

Opening a connection takes time. Reuse it:

$sessions = New-PSSession -ComputerName $servers
Invoke-Command -Session $sessions -ScriptBlock { Get-HotFix | Select-Object -Last 1 }
Invoke-Command -Session $sessions -ScriptBlock { Get-Service W3SVC }
Remove-PSSession $sessions

Handle servers that fail

$result = Invoke-Command -ComputerName $servers -ScriptBlock { hostname } `
    -ErrorAction SilentlyContinue -ErrorVariable failed
$failed | ForEach-Object { "$($_.TargetObject): $($_.Exception.Message)" }

That gives you a list of the servers that didn’t answer, so your report is complete.

Credentials – safely

$cred = Get-Credential        # prompts; the password stays encrypted in memory
Invoke-Command -ComputerName SRV01 -Credential $cred -ScriptBlock { whoami }

Never put passwords in scripts. In automation tools (Jenkins, GitHub Actions), use their credential store – see the Jenkins track.

Common problems

Error Usual cause
WinRM cannot complete the operation WinRM not running, firewall blocking 5985, or wrong name
Access is denied Your account isn’t a local admin (or in Remote Management Users) on the target
The WinRM client cannot process the request… TrustedHosts Connecting by IP or to a non-domain machine – use the DNS name, or configure HTTPS/TrustedHosts carefully
Commands work locally but fail remotely on a network share The second hop: your credentials aren’t passed on from the remote server. Avoid the hop, or use approved delegation

FAQ

Is remoting safe to leave enabled? Yes, when it’s limited to admin networks with the firewall and only admins have rights. It’s far safer than RDP for routine admin work, because it’s scriptable and logged.

What’s next

Next: Inventory reports with CIM.

Practise this topic

Test yourself with free questions on this topic – instant answers and explanations.

Start practice questions

PowerShellRemotingWinRMAutomationIntermediate

Gopinath Karthikeyan

Gopinath Karthikeyan – Windows Site Reliability Engineer with about 12 years in enterprise Windows Server infrastructure, and founder of WinOps Academy. YouTube · LinkedIn

More in PowerShell