1

I have a task running a mercurial command that fails because mercurial is not returning 0 but 1.

When mercurial returns 1 does not mean it's an error but there is nothing to do. According to the documentation:

Returns 0 if push was successful, 1 if nothing to push.

How can I handle the return in my task so when the hg command returns 0 or 1 it won't break.

Here is the failing function

Function Invoke-HgBookmark([string]$bookmarkname)
{
    $repo = GetCredentials
    & $hg.file bookmark -f $bookmarkname
    Invoke-Expression "$($hg.file) push -B $bookmarkname $repo"
    if ($LASTEXITCODE -eq 0 -Or $LASTEXITCODE -eq 1)
    {
        return 0
    }
    else
    {
        return -1
    }
}

Psake is calling my function with this code:

try {
    $global:lastexitcode = 0                 
    & $cmd
   if ($lastexitcode -ne 0) {
        throw ("Exec: " + $errorMessage)
    }
    break
}
JuChom
  • 5,717
  • 5
  • 45
  • 78
  • It looks like your function is trying to handle the exit code of 1. Is the function returning `-1` or failing in some other way? If it is returning `-1` - stick in a `Write-Host "$LastExitCode"` to see what exit code you are getting. Your `if` expression logic looks good. BTW what's with the Invoke-Expression? I don't see why you can't invoke $hg.file like you do in the line above the iex. – Keith Hill Jan 06 '14 at 14:53
  • Actually, I'm learning powershell... I don't need iex. Back to my problem I added the code psake is using and I can't overwrite the $lastexitcode in case hg returns 1 – JuChom Jan 06 '14 at 15:35
  • Ah, in that case try replacing `Return x` with `$LastExitCode = x`. – Keith Hill Jan 06 '14 at 16:01
  • $LastExitCode does not work, $global:lastexitcode = 0 is working fine. Not very sure why... I will try to dig a little bit and write a decent answer – JuChom Jan 06 '14 at 16:08
  • Yeah that makes sense. When you set $LastExitCode in your script it modifies the value for the scope of the function where it is set. So yeah, I should have said to use `$global:LastExitCode = x`. – Keith Hill Jan 06 '14 at 18:51

1 Answers1

3

In the function, set $global:LastExitCode to the desired value before it exits. You have to use the global: prefix in order to modify the global variable. Otherwise PowerShell does a "copy-on-write" operation and modifies a variable with the same name that is local to the function.

Keith Hill
  • 194,368
  • 42
  • 353
  • 369