Cataster
Cataster

Reputation: 3541

Is there an alternative to "exit" in PowerShell?

I have a synchronize powershell script that syncronizes 1 cube on two different servers.

i have a flag set for each of the two servers, where three scenarios can happen:

1: BOTH servers TRUE

2: BOTH servers FALSE

3: 1 server TRUE, the other server FALSE

scenario one exit code is 0 (successful syncing)

scenario two exit code is 1 (failed syncing)

but for scenario 3, if one server is set to false, exit would be 1 for failed, but the script SHOULD continue running because the other server is available to sync on, with an exit code of 0 for success.

the problem with exit is it exits the remainder of the script when its called. I would like an alternative to this exit mechanism to cover scenario 3. I have found the closest thing is this:

[ $PS1 ] && return || exit;

or

[ -v PS1 ] && return || exit

but i am unsure how to pass a code there (0 or 1), let alone i received errors that the command is not recognized anyways.

Missing type name after '['.

The token '||' is not a valid statement separator in this version.

The token '&&' is not a valid statement separator in this version.

The reason I need exit codes is because they are passed back to the batch file as such:

    if %errorlevel% NEQ 0 GOTO :error
GOTO :end
:error
REM echo Exit Code: %ERRORLEVEL%
REM echo Failed!

EXIT /B %ErrorLevel%
:end
REM echo Exit Code: %ERRORLEVEL%
REM echo Success!

which third party automation (autosys) depends on to reflect status.

Upvotes: 0

Views: 1732

Answers (2)

Cataster
Cataster

Reputation: 3541

Since there doesnt seem to be an alternative (an exit code passed without exiting), I have instead used a conditional incremental, in which

if ($i -eq 1) # 1 indicates that it ran successfully on just one server (scenario3)
{exit 0} # 0 for success

elseif ($i -gt 1) #if scenario 2 was the case, provide exit 1 for failure on BOTH servers
{ exit 1 }

else {exit 0} #for scenario 1

all my scenarios are now working as intended, solving the exit code issue

Upvotes: 0

Jeremy Anderson
Jeremy Anderson

Reputation: 31

Check out this article. It covers the topic in depth:

https://weblogs.asp.net/soever/returning-an-exit-code-from-a-powershell-script

I don’t want to take away from Serge’s answer (it is somewhat exhaustive), but as a hint, his first conclusion is:

“Don’t use exit to return a value from PowerShell code, but use the following function:

function ExitWithCode 
{ 
  param 
  ( 
      $exitcode 
  )
  $host.SetShouldExit($exitcode) 
  exit 
}

Upvotes: 3

Related Questions