I am trying to run some code if a string does not start with a certain character, however I can not get it to work with multiple characters.
This is the code that works fine.
if (-Not $recdata.StartsWith("1"))
{
//mycode.
}
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 even though PowerShell does not throw any errors.
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:
-in
, the is-the-LHS-contained-in-the-RHS-collection operator
-like
, the wildcard matching operator
-match
, the regular-expression matching operator