Help with exec() function

Welcome Forums General PowerShell Q&A Help with exec() function

Viewing 2 reply threads
  • Author
    Posts
    • #256742
      Participant
      Topics: 2
      Replies: 2
      Points: 26
      Rank: Member

      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

       

    • #256763
      Participant
      Topics: 15
      Replies: 1776
      Points: 3,218
      Helping Hand
      Rank: Community Hero

      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:

    • #257000
      Participant
      Topics: 0
      Replies: 81
      Points: 362
      Helping Hand
      Rank: Contributor

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

       

Viewing 2 reply threads
  • You must be logged in to reply to this topic.