PowerShell Remoting & WS-Management (2/3)
Part 2 of PowerShell Remoting covers the five cmdlets you use every day: Invoke-Command (one command on many computers), New-PSSession (persistent sessions), New-PSSessionOption (timeouts and transport options), New-PSSessionConfigurationFile (restricted .pssc endpoints) and Invoke-WSManAction (WMI methods over WS-Man).
238.1 Why is it used?
- Run the same command on 50 servers in parallel and get objects back tagged with PSComputerName.
- Keep state (variables, imported modules) across several commands with a persistent session.
- Build restricted endpoints so helpdesk users can run only a few cmdlets.
- Call WMI methods (e.g. StartService) directly over WS-Management.
- Target needs WinRM: HTTP 5985 / HTTPS 5986. Invoke-WSManAction is in Microsoft.WSMan.Management, the rest in Microsoft.PowerShell.Core.
238.2 How it works
- Step 1
1.Admin PC: Invoke-Command -ComputerName Server01,Server02 -ScriptBlock {...}
- Step 2
2.ScriptBlock is packed as WS-Management (SOAP over HTTP) to port 5985
- Step 3
3.WinRM listener on each server runs it in wsmprovhost.exe
- Step 4
4.Result objects come back serialized as XML
- Step 5
5.PSComputerName shows which server each object came from
- Step 6
6.At most ThrottleLimit (default 32) connections at once
- Step 1
1.-ComputerName: a new temporary connection per command, closed afterwards
- Step 2
2.So a variable set in command 1 is gone in command 2
- Step 3
3.$s = New-PSSession Server01 keeps one connection open
- Step 4
4.Invoke-Command -Session $s { $p = Get-Process powershell }
- Step 5
5.Invoke-Command -Session $s { $p.VirtualMemorySize } returns 17930240
238.3 Comparison: -ComputerName vs -Session
| Point | -ComputerName | New-PSSession + -Session |
|---|---|---|
| Connection | Temporary, per command | Persistent until Remove-PSSession |
| State between commands | Lost | Kept (variables, modules) |
| Setup cost | Paid on every call | Paid once |
| Best for | One-off commands | Several related commands, shared data |
238.4 Invoke-Command locally (real, no WinRM)
(Get-Command Invoke-Command).ParameterSets.NameInvoke-Command -ScriptBlock { 1+1 }Invoke-Command -ScriptBlock { param($Rows, $Cols) $Rows * $Cols } -ArgumentList 6, 7$x = 1; Invoke-Command -ScriptBlock { $x = 5 }; $x$x = 1; Invoke-Command -ScriptBlock { $x = 5 } -NoNewScope; $xInProcessSessionFilePathRunspaceComputerNameFilePathComputerNameUri...VMNameContainerIdFilePathContainerIdPS> Invoke-Command -ScriptBlock { 1+1 }2PS> ... -ArgumentList 6, 742PS> $x = 1; Invoke-Command -ScriptBlock { $x = 5 }; $x1PS> $x = 1; Invoke-Command -ScriptBlock { $x = 5 } -NoNewScope; $x5- Without -ComputerName the InProcess set runs the scriptblock immediately in a child scope: WinRM plays no role.
- -ArgumentList fills param() by position (6 * 7 = 42).
- -NoNewScope runs in the current scope, so $x becomes 5.
238.5 Invoke-Command options
Invoke-Command -ComputerName S1, S2 -ScriptBlock { Get-Process powershell }PSComputerName Handles NPM(K) PM(K) WS(K) VM(M) CPU(s) Id ProcessName-------------- ------- ------ ----- ----- ----- ------ -- -----------S1 575 15 45100 40988 200 4.68 1392 PowerShellS2 777 14 35100 30988 150 3.68 67 PowerShell| Option | Meaning |
|---|---|
| -ComputerName / -Session | Temporary connection / existing PSSession |
| -ConnectionUri, -Port, -UseSSL | Endpoint (5985 HTTP, 5986 HTTPS) |
| -Credential / -Authentication | Login; Default, Basic, Negotiate, Kerberos, Credssp, Digest... |
| -ScriptBlock / -FilePath | Commands / a local script run remotely |
| -ArgumentList, $Using:var | Pass values / local variables into the remote command |
| -AsJob, -InDisconnectedSession | Background job / keep running in a disconnected session |
| -HideComputerName, -ThrottleLimit | Display only / max concurrent connections (32) |
| -VMName, -ContainerId | Run inside a VM or container |
$s = New-PSSession -ComputerName Server01, Server02Invoke-Command -Session $s -ScriptBlock { Get-EventLog System } -AsJobId Name State HasMoreData Location Command--- ---- ----- ----- ----------- ---------------1 Job1 Running True Server01,Server02 Get-EventLog System238.6 New-PSSession
$Server01 = New-PSSession -ComputerName Server01$s1, $s2, $s3 = New-PSSession -ComputerName Server01,Server02,Server03New-PSSession -ComputerName Server01 -Port 8081 -UseSSL -ConfigurationName E12$rs = Get-Content C:\Test\Servers.txt | New-PSSession -ThrottleLimit 50- Most options match Invoke-Command; -Name gives a friendly name for Get-PSSession.
- -Port 8081 -UseSSL hits a custom listener; -ConfigurationName picks an alternate endpoint.
- Docs show no output and it was not run on the office PC.
238.7 New-PSSessionOption (real, just an object)
New-PSSessionOption | Select-Object OpenTimeout,OperationTimeout,IdleTimeout,CancelTimeout,MaximumConnectionRedirectionCountNew-PSSessionOption -OperationTimeout 30000 -IdleTimeout 600000 | Select-Object OperationTimeout,IdleTimeout,OpenTimeout,NoCompression,NoEncryption,SkipCACheckOpenTimeout : 00:03:00OperationTimeout : 00:03:00IdleTimeout : -00:00:00.0010000CancelTimeout : 00:01:00MaximumConnectionRedirectionCount : 5 OperationTimeout : 00:00:30IdleTimeout : 00:10:00OpenTimeout : 00:03:00NoCompression : FalseNoEncryption : FalseSkipCACheck : False- Values are in milliseconds: 30000 = 30 s, 600000 = 10 min.
- IdleTimeout -1 ms means not set; Open/OperationTimeout default 3 min, CancelTimeout 1 min.
- Other groups: size limits (-MaximumReceivedObjectSize), -NoCompression/-NoEncryption, -SkipCACheck/-SkipCNCheck/-SkipRevocationCheck (e.g. HTTPS by IP), proxy, -Culture, -ApplicationArguments.
238.8 New-PSSessionConfigurationFile (.pssc)
New-PSSessionConfigurationFile -Path $scr\lab.pssc -SessionType RestrictedRemoteServer ` -VisibleCmdlets Get-Date -Author student -Description 'n238 lab'Get-Content $scr\lab.pssc(Get-Content $scr\lab.pssc | Where-Object { $_ -match '^\s*[A-Za-z]' }).Count@{SchemaVersion = '2.0.0.0'GUID = '5d85c67b-e9c5-4190-9b18-5fe78cae33e1'Author = 'student'Description = 'n238 lab'SessionType = 'RestrictedRemoteServer'VisibleCmdlets = 'Get-Date'}# Directory to place session transcripts for this session configuration# TranscriptDirectory = 'C:\Transcripts\'# Whether to run this session configuration as the machine's (virtual) administrator account# RunAsVirtualAccount = $true# Cmdlets to make visible when applied to a session...6- Only writes a text file; nothing is registered. Only -Path is required; every omitted parameter becomes a comment.
- -SessionType Empty | RestrictedRemoteServer | Default; -LanguageMode NoLanguage | RestrictedLanguage | ConstrainedLanguage | FullLanguage.
- -Visible* options limit cmdlets, functions, aliases, providers, external commands; also -RoleDefinitions, -RunAsVirtualAccount, -TranscriptDirectory.
New-PSSessionConfigurationFile -Path .\NoLanguage.pssc -LanguageMode NoLanguageRegister-PSSessionConfiguration -Path .\NoLanguage.pssc -Name NoLanguage -ForceInvoke-Command -Session $NoLanguageSession -ScriptBlock { if ... }The syntax is not supported by this runspace. This might be because it is in no-language mode. + CategoryInfo : ParserError: (if ((Get-Date) ...') {'Before'} :String) [], ParseException + FullyQualifiedErrorId : ScriptsNotAllowed + PSComputerName : localhost238.9 Invoke-WSManAction
- Step 1
1.Admin PC sends Action StartService
- Step 2
2.ResourceURI wmicimv2/Win32_Service + SelectorSet @{name='spooler'}
- Step 3
3.Server01 runs Win32_Service.StartService() through WMI
- Step 4
4.ReturnValue comes back: 0 = success, 5 = already started
$params = @{ Action = 'StartService' ResourceURI = 'wmicimv2/Win32_Service' SelectorSet = @{name = 'spooler'} Authentication = 'Default' }Invoke-WSManAction @paramsxsi : http://www.w3.org/2001/XMLSchema-instancep : http://schemas.microsoft.com/wbem/wsman/1/wmi/root/cimv2/Win32_Servicecim : http://schemas.dmtf.org/wbem/wscim/1/commonlang : en-USReturnValue : 0- -Action and -ResourceURI are required; -ValueSet, -FilePath, -OptionSet pass input; -ConnectionURI http://server01:5985/wsman.
- Not run on the office PC because it changes real services.
238.10 Linux equivalent lab (SSH fan-out and reuse)
ssh ops@web1 'hostname; whoami; uname -r'time sh -c 'for h in web1 web2; do ssh ops@$h "sleep 2; echo $(hostname) ok"; done'time sh -c 'for h in web1 web2; do ssh ops@$h "sleep 2; echo $(hostname) ok" & done; wait'P='-o ControlPath=/tmp/cm-%h'ssh $P -o ControlMaster=auto -o ControlPersist=60 ops@web1 'echo first'ssh $P -O check ops@web1time ssh $P ops@web1 'echo reused'web1ops6.18.54.1-microsoft-standard-WSL2+ sequential loopweb1 okweb2 okreal 0m 5.45s+ parallel loop (&, wait)real 0m 2.86sfirstMaster running (pid=60)reusedreal 0m 0.08s- Sequential ssh: 5.45 s; parallel in the background: 2.86 s, like Invoke-Command fan-out.
- ControlMaster keeps one master connection; the reused command took 0.08 s, like a persistent New-PSSession.
238.11 Common mistakes
- Expecting a variable to survive between two -ComputerName calls: use New-PSSession + -Session.
- Thinking OperationTimeout limits command run time: it only governs WinRM connection tests and has no effect on SSH remoting; use -AsJob or a disconnected session for long work.
- Referencing a local variable remotely without $Using: or -ArgumentList.
- Forgetting that a .pssc file does nothing until registered.
238.12 Interview tips
- 50 servers: Invoke-Command -ComputerName list, parallel with ThrottleLimit 32, results tagged with PSComputerName.
- Shared data: New-PSSession, then Invoke-Command -Session.
- $Using: for local variables, -AsJob for long jobs.
- Restricted endpoint: .pssc with RestrictedRemoteServer + Visible* + NoLanguage, then Register-PSSessionConfiguration.