Go Back   TechArena Community > Software > Software Development
Become a Member!
Forgot your username/password?
Tags Active Topics RSS Search Mark Forums Read

Reply
 
Thread Tools Search this Thread
  #1  
Old 07-02-2009
Member
 
Join Date: May 2008
Posts: 979
Problem with exit code in Powershell

I am developing a code in Powershell. My problem is that I am unable to figure out how to get the exit code from a batch file that I have executed.

For example, if i have myfirst.bat with

exit /b 1

and myfirst.ps1 with

..\myfirst.bat

$?
$LastExitCode

I get True and 0 output to the console.

How can I determine whether the batch file exited safely or not? It seems like Powershell is getting the return code from "cmd.exe" instead of the batch file. Is there any way to work around this?
Reply With Quote
  #2  
Old 07-02-2009
Member
 
Join Date: May 2008
Posts: 945
Re: Problem with exit code in Powershell

  1. A normal termination will set the exitcode to 0
  2. An uncaught THROW will set the exitcode to 1
  3. The EXIT statement will stop the process and set the exitcode to whatever is specified.

Try running the script like this:

PowerShell ?Command ?& { c:\myfirst.ps1; exit $LASTEXITCODE}?

echo %errorlevel% - Should show what the ps1 script exited with.
Reply With Quote
  #3  
Old 07-02-2009
Member
 
Join Date: Feb 2008
Posts: 194
Re: Problem with exit code in Powershell

Code:
function CheckExitCode {
param ([string]$failureMessage, [int[]]$successCodes = @(0), $finallyScript=$null)

$res = $successCodes -contains $LastExitCode
if ($res.Length -eq 0) {
write-error "ERROR CODE ${LastExitCode}: $failureMessage"
if ($finallyScript) {
"Executing finally:"
&$finallyScript
}
exit 1
}
}
Use like so:

Code:
tf checkin $file /noprompt
CheckExitCode "Checkin of $file" @(0) {tf undo $file /noprompt}
Reply With Quote
  #4  
Old 07-02-2009
XSI XSI is offline
Member
 
Join Date: May 2008
Posts: 271
Re: Problem with exit code in Powershell

Code:
$host.SetShouldExit($exitcode)
$host is a PowerShell reserved variable, and
$exitcode is the INT you want your script to return when it exits.
Reply With Quote
Reply

  TechArena Community > Software > Software Development
Tags: ,



Thread Tools Search this Thread
Search this Thread:

Advanced Search


Similar Threads for: "Problem with exit code in Powershell"
Thread Thread Starter Forum Replies Last Post
Service Exit code 0x240001 kyosang Server Update Service 1 19-12-2012 01:25 PM
The task completed with an exit code of (1) Ikram Active Directory 3 03-09-2009 05:45 AM
Exit code from a batch file? Bhairav Operating Systems 3 17-02-2009 05:38 PM
Scheduled Task Exit Code Rich Young Windows Server Help 6 07-01-2008 11:41 AM
Task Scheduler Exit Code GMC Windows Server Help 4 21-04-2007 07:51 AM


All times are GMT +5.5. The time now is 03:17 AM.