0

Essentially I need to start my conditional using by implying 3 different conditions.

If the exit code is 1 or 2 or 3 they script must do something if anything else do something else:

if ( $LASTEXITCODE -eq 1 or $LASTEXITCODE -eq 2 or $LASTEXITCODE -eq 3 or  ) {

}

What is the correct syntax for the code above?

5
  • 2
    -or is the operator. Use an else statement for the other condition Commented Jun 9, 2020 at 14:46
  • So my sample code is correct just put a dash in front of the or? Commented Jun 9, 2020 at 15:01
  • Your code will do the condition if $lastexitcode is 1, 2, or 3. Is this intended or were you looking for elseif? Commented Jun 9, 2020 at 16:44
  • Another approach could be if ( $LASTEXITCODE -ge 1 -and $LASTEXITCODE -le 3) Commented Jun 9, 2020 at 16:46
  • Learn basic powershell. Commented Jun 9, 2020 at 17:17

2 Answers 2

1

The logical OR operator in PowerShell is prefixed with -, so that would be:

if($LASTEXITCODE -eq 1 -or $LASTEXITCODE -eq 2 -or $LASTEXITCODE -eq 3){

}

For a more concise way of testing for this condition you would leverage the -contains or -in containment operators:

if($LASTEXITCODE -in 1,2,3){ ... }
# or 
if(1,2,3 -contains $LASTEXITCODE){ ... }
Sign up to request clarification or add additional context in comments.

Comments

0

If $LastExitCode is always greater than 0 you could just use:

If ($LastExitCode -lt 4)  {#do for 1,2,3}
Else (#do for 4+}

If $LastExitCode could be zero:

Switch ($LASTEXITCODE) {
   0                   {"Zero"}
   {1..3 -Contains $_} {"Range 1-3"}
   Default             {"Greater than 3"}
}

HTH

1 Comment

Careful, this would also evaluate to $true for $LASTEXITCODE = 1 :)

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.