30

I found that

$(Invoke-Expression hostname) -eq 'mycomputername'

Whether it is matched or not, the exitcode must be 0 this behavior is different from linux ,i.e, if not match error code exit 1

Is there any short command in PowerShell that can return error exit code if doesn't match the string?

4 Answers 4

32

In an script you can change exit code using exit keyword.

A normal termination will set the exitcode to 0

An uncaught THROW will set the exitcode to 1

The EXIT statement will stop the process and set the exitcode to whatever is specified.

In your case I'ld do something like this

if ( $(hostname) -eq 'mycomputername')
{
  exit 0
}
else
{
  exit 1
}
Sign up to request clarification or add additional context in comments.

1 Comment

An uncaught THROW did not set the exitcode to1 for me, on PowerShell v3.0.
1

Minor update, you can simplify this these days:

powershell -command "if($(Invoke-Expression hostname) -ne 'wrongname'){ exit 1 }"
echo Error=%ERRORLEVEL%

Comments

0

Are you looking for something like this?

C:\>powershell -command "& { if($(Invoke-Expression hostname) -eq 'wrongname'){ exit 0 } else { exit 1 }  } "
C:\>echo %errorlevel%
1

C:\>powershell -command "& { if($(Invoke-Expression hostname) -eq 'rightname'){ exit 0 } else { exit 1 }  } "
C:\>echo %errorlevel%
0

5 Comments

yes you are right is there any better way to do ? looks like very clusmy
@KitHo Might be. Can you explain a bit more what you are trying to achieve? Streamlining depends on intended use case.
What i want to achieve is that compare the hostname , it is matched string, it will return exit code 0, otherwise return exit code 1
@KitHo Look up the XY problem.
what do u mean XY problem
0

If you're wanting it more succint,

powershell -command "& { if($(Invoke-Expression hostname) -ne 'wrongname'){ exit 1 } }"

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.