8

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

1
  • 1
    Do you really get True, False, False, False, False? I expect it would be True, True, True, True, True, because not empty string result in $true, when converted to [bool]. So, your logical expression equivalent to ($User -match "administrator") -or $true, which should always return $true. Commented Apr 12, 2017 at 1:41

2 Answers 2

14

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Awesome thanks! I could swear I used that before and it didn't work... well now it's working.
4

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.