Statements has no effect (if/else) in PS

I'm working on a script that gets executed only if X account is found, but is not working as intended the if/else statements get bypassed and the code gets executed anyways. What am i doing wrong?

$Account = "XXXX"
Get-LocalUser -name $Account

if (($Account) -eq $true)  {
 } else {
Write-host -foreground cyan "I found it" 
}
exit

If i ran the script as is it will output the text on the console even tho "XXX" account is not present, could something like that can be done?


This should do it:

$Account = "XXXX"
$AccountObject=Get-LocalUser -name $Account -ErrorAction SilentlyContinue

if (($AccountObject))  {
  Write-host -foreground cyan "I found it" 
} else {
  Write-host -foreground cyan "No luck"
} 

The issue with the sniplet provided - the return of Get-LocalUser was not used. Instead you were using a string value which is always set therefore true - as you set it to 'XXXX' in your first line.


As Bill_Stewart explains, the reason that the else block is reached is because ($Account) -eq $true evaluates to $false unless the account name is "true".

In order to test whether Get-LocalUser succeeded or failed to retrieve the user account, you can instead inspect the $? automatic variable - it will have a value of $false only if the previous command threw an error:

$AccountName = "nonExistingUser"

# Try to fetch existing user account, don't show any errors to the user
$UserAccount = Get-LocalUser -Name $AccountName -ErrorAction SilentlyContinue

# Test if the call was successful
if($?) {
    Write-Host "Found account named '$AccountName'!" -ForegroundColor Cyan
    $UserAccount
} else {
    Write-Host "No account named '$AccountName' was found ..." -ForegroundColor Magenta
}