chocolatey powershell lastexitcode

Status
Not open for further replies.
I'm trying to set up a chocolatey extension module for in-house deployments that does some common housekeeping tasks for our apps. Part of that housekeeping is backing up the existing app install via robocopy in chocolateybeforemodify. The problem is that robocopy doesn't use 0 to mean success so then chocolatey fails because the $lastexitcode is != 0.

I'm tempted to just do this in my function, $global:LASTEXITCODE = $null, but I know it isn't recommended. Is there a better way? I don't want to have my calling code return a different exit code based on current $lastexitcode because then my calling code is making assumptions about how I am doing the backup in this module.

Here is my function, in case it makes any difference.

Code:
function Backup-App([string] $appPath, [string] $appsRoot, [string] $appName){
	
	# if the directory doesn't exist, then just return
	if(!(Test-Path $appPath)){ return }
	
	# back up the app
	Write-Host "Backing up ${appPath}"
	$installDate = $(get-date -f yyyyMMdd.HHmm)
	$backupRoot = "${appsRoot}\..\backups"
	$backupPath = "${backupRoot}\${appName}-${installDate}"
	$logPath = "${backupRoot}\${appName}-backup-$installDate.log"

	if(!(Test-Path "${backupRoot}")){
		New-Item -ItemType Directory -Path "${backupRoot}"
	}
	robocopy ${appPath} "${backupPath}" /MIR /LOG:"${logPath}"
}
 
[url=http:/civis/viewtopic.php?p=32538615#p32538615:37wzuiis said:
Jackass JoeJoe[/url]":37wzuiis]The solution, then, is to test $LASTEXITCODE yourself and use "exit #" to produce the required code.

Except this function is in a module which called by other scripts. Those scripts may call several items and shouldn't need to know why some module function set $lastexitcode. In fact, they should be able assume that any non-zero $lastexitcode means something went wrong.

Using "exit #" from a function isn't going to produce the desired results.
 
As a reference,

first.ps1
Code:
Invoke-Expression ".\second.ps1"
Write-Host "Done. Code=$($LASTEXITCODE)"

second.ps1
Code:
if ($true) {
exit 1
} else {
exit 0
}
Write-Host "This will never print."


The result of running first.ps1:
Done. Code=1

"Exit" will terminate only the script "second.ps1", as expected. It does not terminate the calling script. A "return" will exit the current code block.
 
Status
Not open for further replies.