Miguel De Santiago
Miguel De Santiago

Reputation: 83

powershell -Or operator not working

Can someone tell me why the -or does not work. If I run the code the first output is administrator which returns true but when it gets to the kahuna account it still returns false not true.

(Get-LocalUser).Name | Out-File C:\localusers.txt

ForEach ($User in Get-Content C:\localusers.txt)
{
    If ($User -match "administrator" -or "kahuna")
    {
        Write-Host True
    }
    Else
    {
        Write-Host False
    }
}

I get

True, False, False, False, False

Here are the accounts listed in order they appear

administrator, DefaultAccount, Guest, Kahuna, PCUser

Upvotes: 8

Views: 17410

Answers (2)

sadtank
sadtank

Reputation: 340

Nick is right, vote up his answer. You can also use parens if that is easier to see:

 If (($User -match "administrator") -or ($User -match "kahuna"))

The parens are implied and PSH sees them there anyway. With or without the parens, $User = "administrator" would first resolve to:

If (($true) -or ($false))

which resolves to $true.

Upvotes: 4

Nick
Nick

Reputation: 1863

Try

If ($User -match "administrator" -or $User -match "kahuna")

Your -or operator doesn't tie the values of the previous operator together. You need to specify a 2nd conditional operator after -or I believe.

Upvotes: 14

Related Questions