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?
$? Contains the execution status of the last command. It contains True if the last command succeeded and False if it failed. For cmdlets and advanced functions that are run at multiple stages in a pipeline, for example in both process and end blocks, calling this.
Use the command Exit $LASTEXITCODE at the end of the powershell script to return the error codes from the powershell script. $LASTEXITCODE holds the last error code in the powershell script.
In Cmd.exe, %ErrorLevel% is a builtin variable which indicates the success or failure of the last executable run. In PowerShell, we support: $? Contains True if last operation succeeded and False otherwise.
The $Error automatic variable contains an array of error objects in the current session. The array of objects can be piped to Get-Error to receive detailed error messages. In this example, $Error is piped to the Get-Error cmdlet. the result is list of detailed error messages, similar to the result of Example 1.
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With