Powershell if String.StartsWith() multiple strings

Viewed 903

I am very new to PowerShell and i am trying run some code if a string does not start with a certain character, however i can not get this to work with multiple characters.

This is the code that works fine.

 if (-Not $recdata.StartsWith("1"))
            {
                //mycode.
            }

But what i want is multiple checks like this

 if (-Not $recdata.StartsWith("1") -Or -Not $recdata.StartsWith("2"))
            {
                //mycode.
            }

But this does not work it breaks the whole function eventhough powershell does not throw any errors. I have tried multiple things but i cant find any solution

1 Answers

MundoPeter has pointed out the logic flaw in your approach - -or should be -and - and Santiago Squarzon has offered an alternative based on the regex-based -match operator.

Let me offer the following PowerShell-idiomatic solutions, taking advantage of the fact that PowerShell's operators offer negated variants simply by prepending not to their names:

$recdata[0] -notin '1', '2' # check 1st char of LHS against RHS array
$recdata -notlike '[12]*'   # check LHS against wildcard expression
$recdata -notmatch '^[12]'  # check LHS against regex

See also:

Related