Skip to content

Instantly share code, notes, and snippets.

@pinecones-sx
Created April 26, 2017 21:20
Show Gist options
  • Save pinecones-sx/13407adacf78457d6ab07c9392ab052a to your computer and use it in GitHub Desktop.
Save pinecones-sx/13407adacf78457d6ab07c9392ab052a to your computer and use it in GitHub Desktop.
If (-Not (Test-Path function:global:Get-LoggedOnUser)) {
function global:Get-LoggedOnUser{
param([string]$targetPC = 'localhost')
$results = Invoke-Command -ComputerName $targetPC -ArgumentList $targetPC -ScriptBlock {
$Computer = $args[0]
If ($Computer -eq 'localhost'){$Computer = $env:COMPUTERNAME}
query user 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,ComputerName,SessionName,Id,State,IdleTime,LogonTime
}
}
Return $results
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment