I create a new PS session to localhost for which I’m using custom configuration, the session is called “RemoteSession” and I store it into variable for later use, ex:
Set-Variable -Name SessionInstance -Value (New-PSSession @PSSessionParams)
Session state after creation:
Id Name Transport ComputerName ComputerType State ConfigurationName Availability
-- ---- --------- ------------ ------------ ----- ----------------- ------------
7 RemoteSession WSMan localhost RemoteMachine Opened LocalFirewall.Core Available
3 wincompat-loca… WSMan localhost RemoteMachine Opened Microsoft.PowerShell Available
Whenever I run Invoke-Command
(and I run it a lot) I use -Session
parameter to specify session to localhost, ex:
Invoke-Command -Session $SessionInstance -ScriptBlock { /* code here */ }
Calling Invoke-Command
this way works up until at some point the session changes from Opened
to Closed
or from “Opened” to “Broken”, ex:
PS> Get-PSSession
Id Name Transport ComputerName ComputerType State ConfigurationName Availability
-- ---- --------- ------------ ------------ ----- ----------------- ------------
5 RemoteSession WSMan localhost RemoteMachine Closed LocalFirewall.Core None
3 wincompat-loca… WSMan localhost RemoteMachine Opened Microsoft.PowerShell Available
Other times it’s just “Broken” instead of “Closed”:
PS> Get-PSSession
Id Name Transport ComputerName ComputerType State ConfigurationName Availability
-- ---- --------- ------------ ------------ ----- ----------------- ------------
7 RemoteSession WSMan localhost RemoteMachine Broken LocalFirewall.Core None
3 wincompat-loca… WSMan localhost RemoteMachine Opened Microsoft.PowerShell Available
My session to localhost somehow changed to “Closed” and sometimes to “Broken” state.
Because it’s closed or broken I can no longer use that session to run commands in Invoke-Command
My question is:
- What does “Closed” mean?
- What does “Broken” mean?
- Why does my session change from “Opened” to “Closed” or to “Broken”?
- How do I keep my session in “Opened” state until I manually remove it?
Note:
I do not do anythign with the session except using it for Invoke-Command
I did take a readon MS docs about what session states mean, but there is no mention of “Closed” or “Broken” state:
about Remote Disconnected Sessions - PowerShell | Microsoft Docs