Find and Logoff Disconnected users :: Powershell Script


One of my recently wondered with frequent account lockouts of users accounts due to disconnected users! whose password expired or password changed after last logon time..

You can use ‘quser /server:servername  | ? { $_ -match “Disc” }’ to find the disconnected users

You may use ‘logoff #SessionId /server:servername’ to log them off from the servers

Below script helps in finding the disconnected users and log them of

#*****************************************

# Start of the Script, Author : Vipin

#*****************************************

$server = Read-host “Enter server name”
quser /server:$server | ? { $_ -match “Disc” }|foreach {
$Session = ($_ -split ‘ +’)[2]
$user = ($_ -split ‘ +’)[1]
$idletime= ($_ -split ‘ +’)[4]
Write-host “You are about to log off user $user with session id $Session who is idle for $idletime ”
logoff $Session /server:$server
}

# End of Script

If you have list of server where you want the user session to be checked and logged them of

#*****************************************

# Start of the Script, Author : Vipin

#*****************************************

$ServerList = get-content .\computers.txt
foreach ($server in $ServerList)
{
quser /server:$server | ? { $_ -match “Disc” }|foreach {
$Session = ($_ -split ‘ +’)[2]
$user = ($_ -split ‘ +’)[1]
$idletime= ($_ -split ‘ +’)[4]
Write-host “You are about to log off user $user with session id $Session who is idle for $idletime ”
logoff $Session /server:$server
}
}

# End of Script

NB: If you want to disconnect any specific users instead of disconnected user, use ‘quser /server:$server | ? { $_ -match “username” } ‘

Look for specif user session across a set of servers in an OU

import-module ActiveDirectory

$searchbase = Read-Host “Enter Server OU details”
$user = Read-Host “Enter User ID”

Get-ADComputer -Filter * -SearchBase $searchbase | foreach {
$server = $_.Name
quser /server:$server | ? { $_ -match $user }|foreach {
$Session = ($_ -split ‘ +’)[2]
$user = ($_ -split ‘ +’)[1]
$idletime= ($_ -split ‘ +’)[4]
Write-host “You are about to log off user $user with session id $Session who is idle for $idletime ”
logoff $Session /server:$server
}
}

 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s