DevOps | Scripts | Automation

PowershellTroubleShooting

How to catch: No user exists for * error in PowerShell?

No users exist for * error is generated when we try to get the logged-in users using the cmd command “quser“. The below command will query logged-in users on Server2.

Invoke-Command -ComputerName Server2 -ScriptBlock {quser}
No User Exists Error

The above command generates an error as no user logged in on Server2. Alternatively, you can try the below command to get logged-in users on the remote server.

quser /server:Server2

If you are running the script on the remote server then you can handle this exception using Try/catch block.

Try/Catch method.
Invoke-Command -ComputerName Server2 -ScriptBlock {
    $ErrorActionPreference = "Stop"
     try{ quser }
     catch {"No users logged in"}

}
$ErrorActionPreference = "Stop"
try {
    quser /server:Server2
}

catch {
    Write-Host "No users logged in"
}

If you are using any third-party tool (BladeLogic, Octopus, Ansible, etc) to determine if users are logged in then use the $LASTEXITCODE method.

$LASTEXITCODE method.
$LastExitCode command in PowerShell determines the status of the last executed code. If that is successful then it returns 0, otherwise, it returns a non-zero value.
  quser /server:Server2

  if($LASTEXITCODE -ne 0) {
    $LASTEXITCODE = 0
    Write-Host "No Logged In users found"
  }