List existing sessions in windows with PowerShell

Have you ever had to to find out it there was someone connected to a given server (either directly or either through a remote connection)? I had it yesterday and it created the idea that I should be able to check this regularly (or it should be automated) to find a moment where the server can be restarted when no one is actively using it...

The first thing I thought was that there would be a PowerShell script, but unfortunately there isn't. Because of that, I started looking around and found the quser command which returns a csv that can be converted to a PowerShell table.

1(((quser) -replace '^>', '') -replace '\s{2,}', ',').Trim() | ConvertFrom-Csv

This returns a list of objects that can be used to determine who is (or has been) logged in and whether or not the session is still active. The only issue with this result is that an inactive session results in an an empty session column which is parsed incorrectly. This and the result is something that cannot necessarily be used in automation...

In that context it is 'better' to do the parsing of the csv result a bit differently and to take a possibility of an empty session name column into account:

1(((quser) -replace '^>', '') -replace '\s{2,}', ',').Trim() | ForEach-Object {
2    if ($_.Split(',').Count -eq 5) {
3        Write-Output ($_ -replace '(^[^,]+)', '$1,')
4    } else {
5        Write-Output $_
6    }
7} | ConvertFrom-Csv

This results in the same list of objects, but in this case the object is parsed correctly :)

enjoy!

comments powered by Disqus