Is there a way to exit every interactive PowerShell session created by Enter-PSSession
in PowerShell?
I tried something like :
Get-PSSession -ComputerName $computerName -Credential $credential | Exit-PSSession
or
Get-PSSession -ComputerName "my computer name" -Credential username@domain.local | foreach { Exit-PSSession $_ }
But does not seem to be right...
Exit-PSSession : The input object cannot be bound to any parameters for the command either because the command does not take
pipeline input or the input and its properties do not match any of the parameters that take pipeline input.
[...]
Example of Get-PSSession
:
PS C:\Users\username> Get-PSSession -ComputerName $computerName -Credential $credential
Id Name ComputerName ComputerType State ConfigurationName Availability
-- ---- ------------ ------------ ----- ----------------- ------------
36 WinRM7 computerNam RemoteMachine Disconnected Microsoft.PowerShell Busy
37 WinRM4 computerNam RemoteMachine Disconnected Microsoft.PowerShell Busy
38 WinRM2 computerNam RemoteMachine Disconnected Microsoft.PowerShell Busy
39 WinRM5 computerNam RemoteMachine Disconnected Microsoft.PowerShell Busy
40 WinRM3 computerNam RemoteMachine Disconnected Microsoft.PowerShell Busy
and piping Disconnect-PSSession
...
PS C:\Users\username> Get-PSSession -ComputerName $computerName -Credential $credential | Disconnect-PSSession
Id Name ComputerName ComputerType State ConfigurationName Availability
-- ---- ------------ ------------ ----- ----------------- ------------
46 WinRM7 computerNam RemoteMachine Disconnected Microsoft.PowerShell Busy
47 WinRM4 computerNam RemoteMachine Disconnected Microsoft.PowerShell Busy
48 WinRM2 computerNam RemoteMachine Disconnected Microsoft.PowerShell Busy
49 WinRM5 computerNam RemoteMachine Disconnected Microsoft.PowerShell Busy
50 WinRM3 computerNam RemoteMachine Disconnected Microsoft.PowerShell Busy
Try Disconnect-PSSession followed by Remove-PSSession:
Get-PSSession -ComputerName $computerName -Credential $credential | Disconnect-PSSession | Remove-PSSession
The Remove-PSSession cmdlet closes PowerShell sessions (PSSessions) in the current session. It stops any commands that are running in the PSSessions, ends the PSSession, and releases the resources that the PSSession was using. If the PSSession is connected to a remote computer, this cmdlet also closes the connection between the local and remote computers.