Skip to content

Instantly share code, notes, and snippets.

@1RedOne
Created December 8, 2015 16:44
Show Gist options
  • Save 1RedOne/64121b5ea44ed962ce01 to your computer and use it in GitHub Desktop.
Save 1RedOne/64121b5ea44ed962ce01 to your computer and use it in GitHub Desktop.
Helping someone on StackExchange
$computername = 'localhost', $env:COMPUTERNAME
foreach ($Computer in $ComputerName) {
try {
quser /server:$Computer 2>&1 | Select-Object -Skip 1 | ForEach-Object {
$CurrentLine = $_.Trim() -Replace '\s+',' ' -Split '\s'
$HashProps = @{
UserName = $CurrentLine[0]
ComputerName = $Computer
}
# If session is disconnected different fields will be selected
if ($CurrentLine[2] -eq 'Disc') {
$HashProps.SessionName = $null
$HashProps.Id = $CurrentLine[1]
$HashProps.State = $CurrentLine[2]
$HashProps.IdleTime = $CurrentLine[3]
$HashProps.LogonTime = $CurrentLine[4..6] -join ' '
$HashProps.LogonTime = $CurrentLine[4..($CurrentLine.GetUpperBound(0))] -join ' '
} else {
$HashProps.SessionName = $CurrentLine[1]
$HashProps.Id = $CurrentLine[2]
$HashProps.State = $CurrentLine[3]
$HashProps.IdleTime = $CurrentLine[4]
$HashProps.LogonTime = $CurrentLine[5..($CurrentLine.GetUpperBound(0))] -join ' '
}
New-Object -TypeName PSCustomObject -Property $HashProps |
Select-Object -Property UserName,@{n='IPAddress';exp={(Test-Connection $computer -count 1).IPV4Address }},ComputerName,SessionName,Id,State,IdleTime,LogonTime,Error
}
} catch {
New-Object -TypeName PSCustomObject -Property @{
ComputerName = $Computer
Error = $_.Exception.Message
} | Select-Object -Property UserName,ComputerName,SessionName,Id,State,IdleTime,LogonTime,Error
}
}
#Result
UserName IPAddress ComputerName SessionName Id State IdleTime LogonTime Error
-------- --------- ------------ ----------- -- ----- -------- --------- -----
stephen 127.0.0.1 localhost console 1 Active none 12/8/2015 9:22 AM
stephen 192.168.0.27 BEHEMOTH console 1 Active none 12/8/2015 9:22 AM
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment