Posted On December 25, 2019

PowerShell: Snippet to Detect and Disconnect Active PS Sessions

kimconnect 0 comments
blog.KimConnect.com >> Codes >> 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 *

Related Post

PowerShell: Error While Invoking Functions Containing 2 Parameters

Issue: This function will raise an error when being invoked: function localFunc ($x, $y){ begin{}…

PowerShell: Creating Scheduled Tasks on Remote Servers

This script is deprecated. Here is a better iteration. # scheduledTasksRemote_V0.0.2.ps1# Purpose: to add a…

Setup LAMP using RedHat 7

// Add a new user and set it with root privileges: sudo su useradd {root-user}…