When I run this function in the console it works as expected. However, when the function is run by the service the $QUserToStringOutput is empty because the service cannot find or run quser.exe.
I tried using `$QUserToStringOutput = & quser.exe`, it said it could not be found. I then tried `$QUserToStringOutput = & $ENV:SystemRoot\System32\quser.exe 2>$null` which returned The term 'C:\Windows\System32\quser.exe' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.
Code: Select all
Function Get-UserSessions{
Try{
$QUserToStringOutput = cmd.exe /C $Env:SystemRoot\System32\quser.exe 2>$null
If(!$QUserToStringOutput){
New-ServiceEvent -EventID 920 -Severity "Error" -Message "Failed to query user sessions."
}else{
$UserSessions = @()
ForEach($Record in $QUserToStringOutput){
# Skip the 'column titles' row from quser
If($Record -match "logon time"){Continue}
$Additional = (Get-LocalUser -ErrorAction Stop | Where-Object{ $_.Name -eq $Record.SubString(1, 20).Trim()} | Select-Object *)[0]
$UserSessions += @{
Username = [string]$Record.SubString(1, 20).Trim()
FullName = [string]$Additional.FullName
SID = [string]$Additional.SID
PrincipalSource = [string]$Additional.PrincipalSource
SessionName = [string]$Record.SubString(23, 17).Trim()
ID = [int]$Record.SubString(42, 2).Trim()
State = [string]$Record.SubString(46, 6).Trim()
Idle = [int]$Record.SubString(54, 9).Trim().Replace('+', '.')
LogonTime = [string]$Record.SubString(65)
}
}
If($UserSessions.Count -gt 0){
Save-Payload -Target "user" -Data $UserSessions
}
}
}Catch{
New-ServiceEvent -EventID 920 -Severity "Error" -Message "Unable to query user sessions. $($_.Exception.Message)"
}
}
Code: Select all
PS C:\Project> $UserSessions | Convertto-json
[
{
"PrincipalSource": "MicrosoftAccount",
"FullName": "My Name",
"Username": "MyUsername",
"SID": "S-1-5-21-1001",
"ID": 1,
"State": "Active",
"LogonTime": "31/10/2019 11:06",
"Idle": 42,
"SessionName": "console"
},
{
"PrincipalSource": "Local",
"FullName": "",
"Username": "test user",
"SID": "S-1-5-21-1008",
"ID": 2,
"State": "Disc",
"LogonTime": "31/10/2019 12:38",
"Idle": 42,
"SessionName": ""
}
]
Does anyone have any tacit knowledge to share? I'm assuming this is a quirk when creating a service over a simple script..?