We help IT Professionals succeed at work.

Powershell script to logoff user from all computers he is logged on to in domain (query domain controllers)

janhoedt
janhoedt asked
on
Hi,

I'm looking for a powershellscript which checks for a certain user AD user, then logs them off from all computers in the domain.
You can query domaincontroller logs for a user, then find the computer and execute a logoff. Why needed? His account is locked and he logged on to several devices, which locks the account again and again.
Had some kind of script,  don't find it anymore.

Thanks!
Comment
Watch Question

Author

Commented:

Thanks, that's the easy part, the logoff.
Specifically need the part where I can see the computers to which a user is logged on.

Author

Commented:
Import-Module ActiveDirectory
$UserName = Read-Host "Please enter username"
#Get main DC
Write-Output "Getting info for logged on user $Username"
$PDC = (Get-ADDomainController -Filter * | Where-Object {$_.OperationMasterRoles -contains "PDCEmulator" })
#Get user info
$UserInfo = Get-ADUser -Identity $UserName
#Search PDC for lockout events with ID 4740
$LockedOutEvents = Get-WinEvent -ComputerName $PDC.HostName -FilterHashtable @ {LogName= 'Security' ;Id= 4740 } -ErrorAction Stop | Sort-Object -Property TimeCreated -Descending
#Parse and filter out lockout events
Write-Output "Done"
Write-Output "Showing results"
$Overview = Foreach ($Event in  $LockedOutEvents)
  {
    If ($Event | Where  {$_.Properties[ 2 ].value -match $UserInfo.SID.Value})
    {
      $Event | Select-Object -Property @ (
        @ {Label = 'User' ; Expression = {$_.Properties[ 0 ].Value}}
        @ {Label = 'DomainController' ; Expression = {$_.MachineName}}
        @ {Label = 'EventId' ; Expression = {$_.Id}}
        @ {Label = 'LockoutTimeStamp' ; Expression = {$_.TimeCreated}}
        @ {Label = 'Message' ; Expression = {$_.Message -split "`r"  | Select -First 1 }}
        @ {Label = 'LockoutSource' ; Expression = {$_.Properties[ 1 ].Value}}
      )
    }}
$Overview | Out-GridView
Write-Output 'Done'
$ComputersToLogoff = $Overview.LockoutSource | select -Unique
$Confirm = Read-Host "Are you sure you want to logoff all sessions for username $username ? Y/N"
if  ($confirm -eq 'Y' ){ foreach  ($Computer in  $ComputersToLogoff) {
    $sessionId = ((quser /server:$Computer | Where-Object { $_ -match $userName }) -split ' +' )[ 2 ]
    if  ($sessionId){
    Write-Host "Logging of $UserName with $SessionId from $Computer"
    logoff $sessionId /server:$Computer
    Write-Host "Checking if logoff was succesfull"
    }
    else  {Write-Host "No sessionid found for $Username on $Computer"
}
}
}
else  {Write-Output "Logoff Cancelled" }


Commented:

See latest update.