Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PowerShell: return error exit code if not match a string

Tags:

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?

like image 738
TheOneTeam Avatar asked Feb 20 '14 07:02

TheOneTeam


People also ask

What is $? In PowerShell?

$? 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.

How do I return an exit code in PowerShell?

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.

What is ErrorLevel in PowerShell?

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.

How do you catch error messages in PowerShell?

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.


1 Answers

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
}
like image 138
CB. Avatar answered Oct 02 '22 14:10

CB.