HAS_SESSION
Summary
Description
Identification
PowerShell
function Find-HAS_SESSION {
[CmdletBinding()]
param([Parameter( Position = 0, ValueFromPipeline = $true,ValueFromPipelineByPropertyName = $true )][string[]]$Target, [Parameter(Position = 1)] [string]$OutputPath = "HAS_SESSION.csv" )
begin {
Import-Module ActiveDirectory -ErrorAction Stop
# Write CSV header (overwrites any existing file)
"Computer,Username,SessionName,ID,State,IdleTime,LogonTime" |
Out-File -FilePath $OutputPath -Encoding UTF8 -Force
# Determine list of computers
if ($Target) {
$computers = $Target
}
else {
$computers = Get-ADComputer -Filter * | Select-Object -ExpandProperty Name
}
}
process {
foreach ($computer in $computers) {
try {
# Run 'query user' and join lines into one string
$raw = (query user /server:$computer 2>&1) -join "`n"
# Skip if no sessions
if ($raw -and $raw -notmatch 'No user exists for') {
# Split into lines, skip header
$lines = $raw -split "\r?\n"
foreach ($line in $lines[1..($lines.Count-1)]) {
$line = $line.Trim()
if (-not [string]::IsNullOrWhiteSpace($line)) {
$cols = $line -split "\s{2,}"
if ($cols.Count -ge 6) {
$obj = [PSCustomObject]@{
Computer = $computer
Username = $cols[0].TrimStart('>')
SessionName = $cols[1]
ID = $cols[2]
State = $cols[3]
IdleTime = $cols[4]
LogonTime = ($cols[5..($cols.Count-1)] -join ' ')
}
$obj | Export-Csv -Path $OutputPath -NoTypeInformation -Append
}
}
}
}
}
catch {
[PSCustomObject]@{
Computer = $computer
Username = 'ERROR'
SessionName = ''
ID = ''
State = ''
IdleTime = ''
LogonTime = $_.Exception.Message
} | Export-Csv -Path $OutputPath -NoTypeInformation -Append
}
}
}
}Exploitation
Windows





Mitigation
Detection
Event ID
Description
Fields/Attributes
References
References
Last updated
Was this helpful?