Help with exec() function

Hi,
I am using this exec() function ( https://gist.github.com/jpoehls/2843721 ) in my script where I have couple commands which I am using with this function.
When I am using the function, and create an error in one of the commands - the script continues to execute - it does not fail on the error.
I created another script where I am not using the function and I created an error ( delete some file etc. so I can produce an error):
ex.

& gulp clean
if (! $?) { throw “Gulp clean failed” }
& gulp build
In this case, the script fails and it does not continue on the other tasks - ( task gulp build is skipped)
On the other hand,with exec() function,
ex.

function Exec
{
param(
[Parameter(Mandatory=1)][scriptblock]$cmd,
[Parameter(Mandatory=1)][string]$task
)
& $cmd
if (! $?) {
throw ("$task" + 'failed!') } Exec { gulp clean } "Gulp clean" Exec { gulp build} "Gulp build"

In this case, it gives the error on the screen but continues to run the script with the other tasks - for example continues with gulp build.

How can I resolve this issue and make it stop executing on the first error just like it does when not using exec() function?
Thank you

 

If you look at the Free Resources link on the left, there is a ebook on Error handling. You can try a standard try\catch:

Try {
  $ErrorActionPreference="stop"
  & gulp clean
}
Catch {
  Write-Warning "Failed to find $username. $($_.Exception.Message)"
}

Thanks for the recommendation.
I already tried with try/catch, but again it gives me the error and continues to execute.

You should use automatic variable $LastExitCode for this rather than $?:

 

function Exec
{
    param(
        [Parameter(Mandatory=1)][scriptblock]$cmd,
        [Parameter(Mandatory=1)][string]$task
    )
    & $cmd
    if ($LastExitCode -ne 0) {
       throw (“$task” + ‘failed!’)
}