Home > Back-end >  Logging off all other users on windows server 2016 except the user who is running the script
Logging off all other users on windows server 2016 except the user who is running the script

Time:08-26

I want to logoff all other users from windows server 2016 (both active and disconnected) except the user who is running the script . I tried with below script, it is logging off me too from the computer. Please help me to achieve it....

((Get-WmiObject -Class Win32_Process).getowner().user | Select-Object  -Unique) |% {query session $_ | where-object {($_ -notmatch 'console') -and ($_ -match 'disc') -and ($_ -notmatch 'services')}| logoff}

CodePudding user response:

Guess I should post an answer. Continuing from my comment, seeing as logoff.exe doesn't bind properties like PowerShell cmdlets do when piping to them, youll have to loop through all the results comparing it against the current logged in user, then invoking the utility to log them off via their ID.

Here's my take:

((quser.exe).Trim(' ','>') -replace '\s{20,39}',',,') -replace '\s{2,}',',' | ConvertFrom-Csv | 
    ForEach-Object -Process {
        if ($_.UserName -notmatch "$env:USERNAME") 
        {
            logoff.exe $_.ID
        }
    }

Another option is to just filter using Where-Object to filter out the logged in user before invoking logoff.exe.

((quser.exe).Trim(' ','>') -replace '\s{20,39}',',,') -replace '\s{2,}',',' | Where-Object -FilterScript { $_ -notmatch "$env:username" } |
    ConvertFrom-Csv | 
    ForEach-Object -Process {
        Logoff.exe $_.ID
    }
  • In terms of filtering, I recommend using the latter example.

This is assuming it's being ran on the local server rather than a remote one.

  • Related