confusion about output from if statement

I’m working a script that looks at a remote machine and tells if if there is a user logged in. The script runs however the output gives me both conditions the syntax is posted below:


$machinenames = ‘randomcomputername’
$users = get-wmiobject -class win32_computersystem -computername $machinenames | select -expandproperty username
$result = write-host “no users logged in to $machinename”
if ($users -eq 0) {write-host " $results logged into $machines"} else {write-host “$users logged into $machinenames”}



any insight would be most appreciated :slight_smile:


Write-Host doesn’t generate manageable output to store into anything. It just writes to the screen.

Additionally, $users will never be equal to 0. It may in some cases be $null but those may not register as equal when directly compared.

What you are doing is not correct to give you what you are after. Please be sure to read the help file entirely, especially the parameters and examples.

Not all properties are available by default. So, you must specifically ask for them, and even with that, some things change over time. What you are doing no longer returns anything in the user name.

You need to use the built-in Windows ‘Qwinsta’

or, there’s the built-in Windows command, “query”, located at %SystemRoot%\system32\query.exe

query user /server:SomeComputerName

or install and use this module…

Or use a different .Net class.

All users that have ever logged on a target system

Get-WmiObject -Class Win32_LoggedonUser -ComputerName $env:COMPUTERNAME |
Select-Object -Property Antecedent

Or try pre-built stuff

Find the logged on users on a remote system/s DescriptionThis script should be useful for Helpdesk or other IT Admins to query remote machines to see who is logged on.This could also be useful for Remote Desktop Services or Citrix Admins * Note this scripts also returns non system accounts that are running services.


tagging in on Joel’s pointer… just a heads up…

Agreed, Write-Host, outside of specific needs should not be used, …
Sending things to the screen in general does not require Write anything. It’s a default action.

but… as to the normal pointer go to in order back up such statements.

Write-Host Considered Harmful | Jeffrey Snover's blog

… Jeffrey Snover change his stance on this as of May 2016.

With PowerShell v5 Write-Host no longer “kills puppies”. data is captured into info stream …
Write-Information (Microsoft.PowerShell.Utility) - PowerShell | Microsoft Learn

obsolete …

Sorry :slight_smile: