Home > Software design >  Statements has no effect (if/else) in PS
Statements has no effect (if/else) in PS

Time:01-12

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?

CodePudding user response:

This should do it:

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

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

This will work even though the exception would be thrown if the account is not there. The issue with the sniplet provided - the return of Get-LocalUser was not used. Instead you were using a string value which is always true - as you set it to 'XXXX' in your first line. The LocalUser object has numerous properties so name property can be used to check if it exists.

CodePudding user response:

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
}
  •  Tags:  
  • Related