Powershell: returns an error exit code if it does not match the string

I found that

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

whether it matches or not, the exit code must be 0, this behavior is different from linux, i.e. if it does not match the output of error code 1

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

+4
source share
5 answers

In a script, you can change the exit code using a keyword exit.

Normal completion will set the exit code to 0

Unmounted will THROWset the exit code to 1

The operator exitwill stop the process and set the exit code to everything that is indicated.

In your case, I did something like this

if ( $(hostname) -eq 'mycomputername')
{
  exit 0
}
else
{
  exit 1
}
+6

:

[int]('hostname' -eq $hostname)

0 false 1 true. , , Boolean?

+1

- ?

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
0

If you want to get more succint,

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

Minor update, you can simplify this these days:

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

Source: https://habr.com/ru/post/1527838/


All Articles