$qusertest = quser | Out-String
if ([string]::IsNullOrEmpty($qusertest)){
Restart-Computer -Force
} else {
Write-Output $qusertest; exit 0
}
I am testing out code to automatically reboot computers in a list that are over a certain up time limit and have no users online. This is part of my testing scripts and for some reason, even if the output of the quser command returns information, it will restart the computer no matter what.
Can someone help me understand what logic is that I am missing that causes this?
PS C:\WINDOWS\system32> C:\Users\user\Documents\Working Scripts\qusertest logging.ps1
$qusertest -eq $null => 'False'
$qusertest.Length => '162'
$qusertest =>
' USERNAME SESSIONNAME ID STATE IDLE TIME LOGON TIME
>user rdp-tcp#0 2 Active . 11/24/2025 3:17 PM
'
USERNAME SESSIONNAME ID STATE IDLE TIME LOGON TIME
>user rdp-tcp#0 2 Active . 11/24/2025 3:17 PM
Here is the logging output when testing the code against a live host and below is one when its against a logged out host, one thing is that this code is being sent through a patch management system when being tested against machines. Could that have been causing the issues? I have censored some user information for privacy sake. Also upon testing it today, it does not seem to be giving the same results so it may have been a random error. No changes to the original code set were made.
No User exists for *
$qusertest -eq $null => 'False'
$qusertest.Length => '0'
$qusertest => ''
Restart Required
[string]::IsNullOrEmpty($qusertest)evaluates toFalse.$qusertestvalue that exhibits the symptom?Out-Stringcmdlet seems to ALWAYS add a cr/lf to the end of whatever you send to it. that includes sending it nothing at all - so your test will always return FALSE since there is something there.Out-Stringnot produce the usualcr/lfending. thank you for the info! [grin]Out-String, as an aggregating cmdlet (similar toMeasure-Object, for instance), still produces output in the absence of input, but then omits the trailing newline it normally (and questionably) appends; in other words: without input it outputs an empty string.