PowerShell: Snippet to Detect and Disconnect Active PS Sessions

# Manual Detection

PS C:\Windows\system32> get-pssession
Id Name ComputerName ComputerType State ConfigurationName Availability
-- ---- ------------ ------------ ----- ----------------- ------------
6 Session6 SHERVER007 RemoteMachine Opened Microsoft.PowerShell Available
7 Session7 SHERVER007 RemoteMachine Opened Microsoft.PowerShell Available
# Disconnect sessions as a cleanup routine
$activeSessionIds=(Get-PSSession).Id
if($activeSessionIds){
Remove-PSSession -id $activeSessionIds;
write-host "Session(s) $activeSessionIds disconnected."
}

# Expected Output
Session(s) 6 7 disconnected.

Leave a Reply

Your email address will not be published. Required fields are marked *