Tuesday, June 20, 2017

Powershell Script to remove Active sessions from server

If you want to remove all the active session on a remote computer/server, Please follow the below script . In going forward we can modify the script for number of computers/servers , for that we need to run another for each loop.
#################################################################################
Write-Host -ForegroundColor Yellow "This is tool has made to remove Session from server, For any issues please contact, Swagat Rout"

$server= read-host "Please enter the server name"

quser /server:$server #| Select USERNAME,STATE,LOGON,TIME

$condition= Read-Host "Do you want to remove a session of user,for yes type [y] & No Type [N]"

if ($condition -eq "y")



{
 
$user= Read-Host "Do you want to remove all the session or some specific users, For all type [A]& Specific userType [S]"

if($user -eq "A")



{
 
$sessions = qwinsta /server $server| ?{ $_ -notmatch '^ SESSIONNAME' } | %{

$item = "" | Select "Active", "SessionName", "Username", "Id", "State", "Type", "Device"

$item.Active = $_.Substring(0,1) -match '>'

$item.SessionName = $_.Substring(1,18).Trim()

$item.Username = $_.Substring(19,20).Trim()

$item.Id = $_.Substring(39,9).Trim()

$item.State = $_.Substring(48,8).Trim()

$item.Type = $_.Substring(56,12).Trim()

$item.Device = $_.Substring(68).Trim()

$item}




 
foreach ($session in $sessions)



{
 
if ($session.Username -ne "" -or $session.Username.Length -gt 1)



{
 
$nam= $session.username

#logoff $session.Id /server $server

Write-Host -ForegroundColor Cyan "Sessions has been removed from $server for $nam "



}

}
 
Write-Host -ForegroundColor Cyan "All the sessions has been removed"

Read-Host "Please enter any key to exit"



}
 
elseif($user -eq "S")



{
 
$specificuser = Read-Host "Please enter the UID, Please ensure that user should have active logon session in the list"

#$sesionID=((quser /server:$server | Where-Object { $_ -match "$specificuser" }) -split ' +')[2]

#logoff $sesionID /server:$server

Write-Host -ForegroundColor Cyan "Sessions has been removed from $server for $specificuser"

Read-Host "Please enter any key to exit"



}

}
 
Else
 
 
{
 
Read-Host "Please enter any key to exit"



}

###################################################################################################
 

No comments:

Test Script

############################################################################## #####################################################...