4

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.

5
  • We would need to understand where is your input coming from. Can you provide us with a sample input and your expected output(s)? Commented Jul 15, 2021 at 0:31
  • Data comes over TCP as text. What i want is when i send for example 1 to the script over TCP that it does not execute my code. It does work when i use the first example i posted. but when i try to exclude 1 and 2 the whole code doesnt work anymore and my script executes the code even though i send 1 or 2 Commented Jul 15, 2021 at 0:43
  • 5
    If what you need is to not run your code neither when $recdata starts with "1", neither "2", then you should change the -Or for an -And Commented Jul 15, 2021 at 1:02
  • 4
    You can also do if( $recdata -match '^[^12]' ) { # your code if it does not start with 1 and 2 } Commented Jul 15, 2021 at 1:29
  • How could i add even more checks to this? just add a 3 after the 2 or? Commented Jul 15, 2021 at 10:47

1 Answer 1

7

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:

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

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.