Have you ever need to log a user off of every computer in your company at once? I’m going to keep this post short and sweet with just the core code. Lets take a look shall we. Here is the first part of the code.

$return += (((quser /server:$ComputerName 2> $null) -replace ‘^>’, ”) -replace ‘\s{2,}’, ‘,’) | ForEach-Object {
if ($_.Split(‘,’).Count -eq 5) {
Write-Output ($_ -replace ‘(^[^,]+)’, ‘$1,’)
} else {
Write-Output $_
}
} | ConvertFrom-Csv
$Return = $Return | Where-Object {$_.”IDLE TIME” -like “.”} | ForEach-Object {$_.”IDLE TIME” = $null}

In this code, we are using an old tool called quser which produces a string output of all the current users. So, we need to work with that information. Here we replace the spaces with , and so on so forth. Since the output of disconnected is different and has more , than non-disconnected users we search filter it out with another replace. Then finally we replace all the idle time with nothing to prevent errors while sorting. Now we take all of this csv formatted data and push it into convertfromcsv to create a usable array. which we can use later.

The next part of the code is a simple logoff command. These are older commands.

logoff /server:$computername $Return.ID;

The logoff command requires a computer name and the id. Using the information above we can sort through the output with foreach loops and log the person out. If you place all of that inside another foreach for a list of computers, you can have the script log them off everything and everywhere.

And that’s it. Everything past this point is just fluff and/or error proofing. I hope you all enjoy.