PowerShell Remoting & WS-Management (3/3)
Part 3 of PowerShell Remoting covers checking and preparing WinRM (Test-WSMan, Set-WSManQuickConfig), collecting and closing sessions (Receive-PSSession, Remove-PSSession), editing WinRM's own configuration (WSMan instance cmdlets) and the full endpoint lifecycle (Test/Register/Set/Unregister-PSSessionConfiguration).
239.1 Why is it used?
- Quickly prove a server's WinRM is reachable before troubleshooting further.
- One command to make a new server remoting-ready.
- Pick up results of long scripts after a network drop or the next day.
- Create, change and delete custom endpoints that restrict what remote users can do.
- Set/Register/Unregister need an admin shell; on the office PC only local commands were run.
239.2 On this PC (real)
(Get-Command -Module Microsoft.WSMan.Management | Measure-Object).CountGet-Command Test-WSMan, Set-WSManQuickConfig, New-WSManSessionOption, Test-PSSessionConfigurationFile, Receive-PSSession, Remove-PSSession13CommandType Name Source----------- ---- ------ Cmdlet Test-WSMan Microsoft.WSMan.Management Cmdlet Set-WSManQuickConfig Microsoft.WSMan.Management Cmdlet New-WSManSessionOption Microsoft.WSMan.Management Cmdlet Test-PSSessionConfigurationFile Microsoft.PowerShell.Core Cmdlet Receive-PSSession Microsoft.PowerShell.Core Cmdlet Remove-PSSession Microsoft.PowerShell.Core239.3 How Test-WSMan and Set-WSManQuickConfig work
- Step 1
1.Admin PC 192.168.10.5 runs Test-WSMan -ComputerName Server01 (TCP 5985)
- Step 2
2.Remoting not configured: blocked at the firewall, "WinRM cannot complete the operation"
- Step 3
3.On Server01 run Set-WSManQuickConfig once
- Step 4
4.WinRM starts (Automatic), HTTP listener on any IP, firewall exception added
- Step 5
5.Test-WSMan again: reply with identity, protocol version and product version
Test-WSMan # local computerTest-WSMan -ComputerName "server01"Test-WSMan -ComputerName "server01" -Authentication Default # OS version tooSet-WSManQuickConfig # HTTP listenerSet-WSManQuickConfig -UseSSL # HTTPS listener (cert + firewall manual)(Get-Command Set-WSManQuickConfig).Parameters.Keys | Where-Object { $common -notcontains $_ }UseSSLForceSkipNetworkProfileCheck- Test-WSMan without authentication shows OS 0.0.0 SP 0.0; -Authentication Default also returns the OS version.
- -UseSSL: HTTPS listener, certificate and firewall must be set up manually; -SkipNetworkProfileCheck allows a public network but only from the local subnet.
239.4 Receive-PSSession
- Step 1
1.Admin PC runs a long script in session ITTask on Server01
- Step 2
2.Network outage: script keeps running, session goes Disconnected
- Step 3
3.PowerShell retries every second for 4 minutes
- Step 4
4.Next day another PC runs Receive-PSSession
- Step 5
5.Session becomes Opened and the results come back
$parms = @{ ComputerName = "Server01" Name = "ITTask" OutTarget = "Job" JobName = "ITTaskJob01" Credential = "Domain01\Admin01"}Receive-PSSession @parmsId Name State HasMoreData Location-- ---- ----- ----------- --------16 ITTaskJob01 Running True Server01| Option group | Options |
|---|---|
| Which session | -ComputerName/-ConnectionUri + -Name/-Id/-InstanceId, or -Session object; -ConfigurationName |
| How results arrive | -OutTarget Host (default) | Job, -JobName |
| Connection | -Credential, -Authentication, -Port, -UseSSL, -AllowRedirection, -SessionOption |
- With -OutTarget Job you get a job (ITTaskJob01) and collect results later with Receive-Job.
239.5 Remove-PSSession
Remove-PSSession -Id 1, 2Get-PSSession | Remove-PSSessionGet-PSSession | Format-Table ComputerName, InstanceIdRemove-PSSession -InstanceId fc4e9dfa-f246-452d-9fa3-1adbdd64ae85ComputerName InstanceId------------ ----------------Server01 875d231b-2788-4f36-9f67-2e50d63bb82alocalhost c065ffa0-02c4-406e-84a3-dacb0d677868Server02 4699cdbc-61d5-4e0d-b916-84f82ebede1fServer03 4e5a3245-4c63-43e4-88d0-a7798bfc2414TX-TEST-01 fc4e9dfa-f246-452d-9fa3-1adbdd64ae85- Stops running commands, frees resources and closes the remote connection.
- Pick by -Id, -Name, -InstanceId, -ComputerName, -Session, -VMName or -ContainerId.
- A session object in a variable stays, but its State becomes Closed.
239.6 WSMan instances (WinRM configuration)
New-WSManInstance winrm/config/Listener -SelectorSet @{Transport='HTTPS'; Address='*'} ` -ValueSet @{Hostname="HOST"; CertificateThumbprint="XXXXXXXXXX"}Remove-WSManInstance -ResourceUri winrm/config/Listener ` -SelectorSet @{Address='test.fabrikam.com'; Transport='http'}Set-WSManInstance -ResourceURI winrm/config -ValueSet @{MaxEnvelopeSizekb = "200"}cfg : http://schemas.microsoft.com/wbem/wsman/1/configlang : en-USMaxEnvelopeSizekb : 200MaxTimeoutms : 60000MaxBatchItems : 32000MaxProviderRequests : 4294967295Client : ClientService : ServiceWinrs : Winrs- Every WinRM config item is a resource with a URI, e.g. winrm/config/Listener; -SelectorSet picks the instance.
- New-WSManInstance creates (here an HTTPS listener), Set-WSManInstance modifies (-Fragment = one section), Remove-WSManInstance deletes.
- -ValueSet is case-sensitive: MaxEnvelopeSizeKB fails, MaxEnvelopeSizekb works.
$a = New-WSManSessionOption -OperationTimeout 30000$a | Select-Object OperationTimeout, SkipCACheck, SkipCNCheck, UseUtf16$a.GetType().FullNameConnect-WSMan -ComputerName "server01" -SessionOption $a # docs, not runOperationTimeout : 30000SkipCACheck : FalseSkipCNCheck : FalseUseUtf16 : FalseMicrosoft.WSMan.Management.SessionOption- New-WSManSessionOption builds an object for -SessionOption of the WSMan cmdlets; -OperationTimeout in ms; also -NoEncryption, -SkipCACheck/-SkipCNCheck/-SkipRevocationCheck, proxy options, -SPNPort, -UseUTF16.
239.7 Endpoint lifecycle
- Step 1
1.New-PSSessionConfigurationFile: write a .pssc file
- Step 2
2.Test-PSSessionConfigurationFile: check keys and values
- Step 3
3.Register-PSSessionConfiguration: register the endpoint
- Step 4
4.Set-PSSessionConfiguration: change it (takes effect after WinRM restart)
- Step 5
5.Unregister-PSSessionConfiguration: delete it
Every PSSession uses an endpoint
New-PSSessionConfigurationFile -Path .\n239-lab.pssc -SessionType RestrictedRemoteServer ` -Author student -VisibleCmdlets Get-DateTest-PSSessionConfigurationFile -Path .\n239-lab.pssc# copy with SessionType = 'AdminOnly'Test-PSSessionConfigurationFile -Path .\n239-broken.pssc -VerboseTrueThe member 'SessionType' must be a valid enumeration type"System.Management.Automation.Remoting.SessionType".Valid enumeration values are"Empty,RestrictedRemoteServer,Default".False$s = Register-PSSessionConfiguration -Name MaintenanceShell -StartupScript C:\ps-test\Maintenance.ps1$s | Format-List -Property *dir WSMan:\LocalHost\PluginPSChildName : MaintenanceShellKeys : {Name=MaintenanceShell}Name : MaintenanceShellTypeNameOfElement : Container Name Type Keys---- ---- ----MaintenanceShell Container {Name=MaintenanceShell}microsoft.powershell Container {Name=microsoft.powershell}microsoft.powershell32 Container {Name=microsoft.powershell32}- The StartupScript runs in every new session; if it throws, New-PSSession fails.
| Register option | Meaning |
|---|---|
| -Name | Required |
| -Path / -AssemblyName + -ConfigurationTypeName | From a .pssc file / from a class in a .dll |
| -AccessMode | Disabled | Local | Remote (default Remote) |
| -SecurityDescriptorSddl / -ShowSecurityDescriptorUI | Who may connect |
| -RunAsCredential | Run the endpoint as this account |
| -MaximumReceivedDataSizePerCommandMB / -MaximumReceivedObjectSizeMB | Defaults 50 MB / 10 MB |
Set-PSSessionConfiguration -Name "IncObj" -MaximumReceivedObjectSizeMB 20Set-PSSessionConfiguration -Name "AdminShell" -StartupScript $null # back to defaultWSManConfig: Microsoft.WSMan.Management\WSMan::localhost\Plugin\IncObj\InitializationParameters ParamName ParamValue--------- ----------psmaximumreceivedobjectsizemb 20"Restart WinRM service"WinRM service need to be restarted to make the changes effective. Do you want to run the command "Restart-Service winrm"?[Y] Yes [N] No [S] Suspend [?] Help (default is "Y"): yUnregister-PSSessionConfiguration -Name "MaintenanceShell" -NoServiceRestartGet-PSSessionConfiguration -Name "MaintenanceShell"New-PSSession -ConfigurationName "MaintenanceShell"Restart-Service winrmNew-PSSession -ConfigurationName MaintenanceShellGet-PSSessionConfiguration -Name MaintenanceShell : No Session Configuration matches criteria "MaintenanceShell".Id Name ComputerName State Configuration Availability-- ---- ------------ ----- ------------- ------------1 Session1 localhost Opened MaintenanceShell Available[localhost] Connecting to remote server failed with the following error message : The WS-Management service cannot process the request. The resource URI (http://schemas.microsoft.com/powershell/MaintenanceShell) was not found in the WS-Management catalog.- With -NoServiceRestart the old endpoint still works until WinRM restarts.
- Deleted a default endpoint by mistake? Enable-PSRemoting brings it back.
239.8 Common mistakes
- Taking a Test-WSMan reply as proof that remoting works: it only proves the service and port; Invoke-Command can still say Access is denied (not admin / not in Remote Management Users; workgroup needs TrustedHosts or HTTPS).
- Changing an endpoint with -NoServiceRestart and forgetting Restart-Service winrm.
- Wrong case in -ValueSet keys.
- Unregister with * (all) by accident.
239.9 Interview tips
- Setup to cleanup: Enable-PSRemoting / Set-WSManQuickConfig, Test-WSMan, Invoke-Command / New-PSSession, Receive-PSSession, Remove-PSSession.
- Restricted access: Test-PSSessionConfigurationFile then Register-PSSessionConfiguration -Path.
- Endpoint changes need a WinRM restart.
- WinRM config lives in resources like winrm/config/Listener, edited with the WSManInstance cmdlets.