18 Sessions: remote control with less work
PowerShell sessions let you reuse persistent remote connections so you don’t have to repeatedly specify computer names, credentials, ports, or authentication options every time you run a command. After creating sessions with New-PSSession (over WinRM with -ComputerName or SSH with -HostName), you can list them with Get-PSSession, store them in variables for convenience, and close them with Remove-PSSession to free resources. This approach streamlines both one-to-one interactive remoting and one-to-many command fan-out, reducing friction compared to ad hoc connections created by Enter-PSSession and Invoke-Command alone.
Once sessions exist, you can target them directly. Enter-PSSession accepts a single PSSession (by variable, index, or by passing in the result of Get-PSSession filtered to a specific ComputerName), and it even supports pipeline input from Get-PSSession. Invoke-Command shines with sessions: you can run scripts or commands in parallel across multiple machines by supplying a collection of session objects, including via a parenthetical Get-PSSession call. Although Invoke-Command does not accept PSSession objects from the pipeline, using the -Session parameter with a parenthetical expression provides a clean and flexible pattern. Throughout, remember sessions consume resources until removed or the host shell closes.
Implicit remoting elevates this further by importing commands from a remote module into your local session via Import-PSSession. The remote machine loads its module (for example, ActiveDirectory), and your console receives a temporary module containing proxy commands (optionally prefixed to avoid name collisions). Those commands run on the remote computer and return results to you, though the returned objects are deserialized (no methods), which can limit certain workflows. PowerShell v3 also introduced disconnected sessions: you can Disconnect-PSSession to leave a remote PowerShell running, and later Connect-PSSession—even from another machine as the same user. Administrators should control proliferation of idle sessions using WSMan settings such as IdleTimeout, MaxShellRunTime, MaxShellsPerUser, and MaxConnections to keep environments tidy and reliable.
Lab answers
get-pssession | Remove-PSSession$session=new-pssession –computername localhostenter-pssession $session
invoke-command -ScriptBlock { get-timezone } -Session $sessionInvoke-Command -ScriptBlock {get-eventlog -LogName System
-Newest 20} -Session (Get-PSSession)
5b.Get-ChildItem -Path /var | Measure-Object | select countInvoke-Command -ScriptBlock {Import-Module ServerManager}
Import-PSSession -Session $session -Prefix rem
Get-RemWindowsFeatureRemove-PSSession-Session$session
FAQ
What is a reusable PowerShell session and why would I use one?
A reusable session (PSSession) is a persistent connection to a remote PowerShell instance created withNew-PSSession. It lets you avoid repeatedly specifying computer names, credentials, ports, or auth each time you run a remote command. Sessions reduce connection overhead but do consume resources on both ends, so close them when you’re done.How do I create sessions over WinRM vs SSH?
UseNew-PSSession -ComputerName for WinRM (HTTP/HTTPS) and New-PSSession -HostName for SSH. With WinRM you typically use -Credential; with SSH you might use -UserName and -KeyFilePath. Example: New-PSSession -ComputerName srv01 (WinRM) or New-PSSession -HostName linux01 -UserName admin (SSH).How can I list, store, and close sessions?
List withGet-PSSession. Store in variables for convenience, for example $sessions = New-PSSession -ComputerName srv01,srv02. Close specific ones with Remove-PSSession (e.g., $sessions | Remove-PSSession) or close all with Get-PSSession | Remove-PSSession.How do I enter an interactive remote shell using an existing session?
UseEnter-PSSession -Session with a single PSSession, for example Enter-PSSession -Session $sessions[0]. You can also pipe from Get-PSSession: Get-PSSession -ComputerName SRV02 | Enter-PSSession. Exit with Exit-PSSession; the session remains open for reuse.I forgot which session in my array maps to which computer. How do I pick the right one?
Inspect or filter by properties. For example:$sessions | Select-Object ComputerName,Id or $sessions | Where-Object ComputerName -eq 'SRV02'. Alternatively, skip the variable and do Enter-PSSession -Session (Get-PSSession -ComputerName SRV02).How do I run the same command on multiple computers using sessions?
UseInvoke-Command -Session with an array of PSSessions: Invoke-Command -Session $sessions -ScriptBlock { Get-Process }. You can also supply sessions via a parenthetical command: Invoke-Command -Session (Get-PSSession -ComputerName server1,server2). Note: Invoke-Command doesn’t accept PSSessions from the pipeline.What is implicit remoting and how do I import remote module commands locally?
Implicit remoting creates local proxy commands that execute on a remote machine. Steps: 1) Create a session:$s = New-PSSession -ComputerName SRV02. 2) Ensure the module is loaded remotely (e.g., Invoke-Command -Session $s -ScriptBlock { Import-Module ActiveDirectory }). 3) Import proxies: Import-PSSession -Session $s -Module ActiveDirectory -Prefix rem. You’ll get commands like Get-remADUser that run on SRV02.Where do implicitly imported commands run, and how long do they last?
Proxy commands run on the remote computer and return results to you. The results are deserialized objects (properties only, no methods). The commands are available until you close the shell or the remote session used byImport-PSSession is closed.What are disconnected sessions and how do I use them across machines?
You can disconnect a session withDisconnect-PSSession -Id <id>; the remote PowerShell keeps running. Later, from another machine as the same user, list and reconnect: Get-PSSession -ComputerName COMPUTER2 then ... | Connect-PSSession. Be mindful of cleanup and timeouts so you don’t leave stray sessions running.How can I control session timeouts and limits (cleanup/governance)?
Use the WSMan provider (and/or Group Policy). Key settings: WSMan:\localhost\Shell\IdleTimeout, MaxShellRunTime, MaxShellsPerUser, MaxConcurrentUsers; and WSMan:\localhost\Service\ MaxConnections. Tune these to prevent idle or excessive sessions.
Learn PowerShell in a Month of Lunches, Fourth Edition ebook for free