Sunday, April 1, 2018

Logoff Disconnected Remote Desktop Sessions using PowerShell

AX 2012 users continue to appear active in AX although they have disconnected from their RDP session.  You can manually open Task Manager on each RDP server and logoff users who have disconnected.  Alternatively, save the following commands as a ps1 file and run it against all RDP servers before checking the Online Users in AX to see who is using AX.


$serverName = "localhost"
$sessions = qwinsta /server $serverName | ?{ $_ -notmatch '^ SESSIONNAME' } | %{
    $item = "" | Select "Active", "SessionName", "Username", "Id", "State", "Type", "Device"
    $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
}
foreach ($session in $sessions) {
    if ($session.Username -ne "" -or $session.Username.Length -gt 1) {
        if ($session.State -eq "Disc") {
            Write-Host ("Logged off {0}" -f $session.Username)

            logoff /server $serverName $session.Id
        }
    }
}

No comments:

Post a Comment