locked
Stop a script from executing - Try/Catch RRS feed

  • Question

  • This is driving me nuts... I can't figure out how to stop a script from executing when I encounter an error in a Try/Catch block. I've tried using 'break' but all that does is exit out of the code block I'm in and the script continues. I also tried exit but that didn't work. The break and exit were placed in the Catch block. Any ideas?

    I've done a ton of Googling with no luck.

    Wednesday, July 2, 2014 8:39 PM

Answers

  • Hi BP,

    as Mjolinor pointed out, use return (instead of break) to interrupt a function (and return to the script).

    If you want to terminate the entire script instead, then as Bill pointed out, use exit (instead of break).

    Cheers,
    Fred


    There's no place like 127.0.0.1

    • Marked as answer by Bill_Stewart Tuesday, July 29, 2014 3:06 PM
    Thursday, July 3, 2014 11:37 AM

All replies

  • Usually to stop a script you'd use Return.

    Note that it requires a terminating error in the Try block to invoke the Catch block.  That means you want to use -ErrorAction Stop on your cmdlets in the Try block if you want to catch all the errors.


    [string](0..33|%{[char][int](46+("686552495351636652556262185355647068516270555358646562655775 0645570").substring(($_*2),2))})-replace " "



    • Edited by mjolinor Wednesday, July 2, 2014 8:54 PM
    Wednesday, July 2, 2014 8:49 PM
  • Can't reproduce.


    function Test-Func {
      try {
        throw "Test error"
      }
      catch {
        "Terminating script."
        exit
      }
    }
    
    Test-Func
    "We shouldn't see this."
    

    When I run this script, all I see is the Terminating script line. I don't see We shouldn't see this.

    -- Bill Stewart [Bill_Stewart]

    • Proposed as answer by FWN Thursday, July 3, 2014 11:37 AM
    Wednesday, July 2, 2014 8:56 PM
  • This s what I have. I have a 'Main' Section of a script that uses a custom function I made that connects to a SQL database and runs a query. In the function that does the DB connection I have a try/catch block to stop the script if it can't connect to the database. I used a break in the catch block and it seems to just exit out of the function and continue on with the script. I want it to stop all together.

    Here is my main section that calls the function:

    	TRY
    	{
    		#Determine which query to run based on the execType
    		Switch ($execType)
    		{
    			"new" { Query-IMR $execType $newAcctsQuery }
    			"upd" { Query-IMR $execType $updAcctsQuery }
    			"disable" { Query-IMR $execType $disableAcctsQuery }
    			"enable" { Query-IMR $execType $enableAcctsQuery }
    			default { Log-Results "$date`tSystem`tFailed`tUnable to query IMR database - $queryType is not a valid queryType`t" }
    		}
    	}
    	CATCH
    	{
    		$errorMessage = $_.Exception.Message
    		Log-Results "$date`tSystem`tProcessing Failed`tProcessing stoped due to system error`t$errorMessage"
    	}
    	FINALLY
    	{
    		IF ($errorMessage -eq $null)
    		{
    			#Initiate the provisioning script
    			Invoke-Item -Path $acctProvScriptFilePath "$execType" "$outputFilePath"
    		}
    	}
    	$errorMessage.Clear()

    And here is the Try/Catch in the Query-IMR function:

    	###Open the connection to the database
    	TRY
    	{
    		$Connection.open()
    	}
    	CATCH
    	{
    		$errorMessage = $_.Exception.Message
    		Log-Results "$date`tSystem`tProcessing Failed`tCould not connect to $dbServer\$dbName`t$errorMessage"
    		break
    	}
    	FINALLY
    	{
    		IF ($errorMessage -eq $null)
    		{
    			Log-Results "$date`tSystem`tProcessing Started`tConnected to $dbServer\$dbName. Initializing Query Type: $queryType`t"
    		}
    	}
    	$errorMessage.Clear()

    Thursday, July 3, 2014 11:28 AM
  • Hi BP,

    as Mjolinor pointed out, use return (instead of break) to interrupt a function (and return to the script).

    If you want to terminate the entire script instead, then as Bill pointed out, use exit (instead of break).

    Cheers,
    Fred


    There's no place like 127.0.0.1

    • Marked as answer by Bill_Stewart Tuesday, July 29, 2014 3:06 PM
    Thursday, July 3, 2014 11:37 AM
  • " I want it to stop all together." is not a very technical statement. Stop what?  You want it to quite PowerShell?  If you want to quite PowerShell use "Exit".

    You are overcomplicating this. It does not require so much code to do the job once you think about what is happening. If you exit there will be no message to test. You do not need to clear or save anything. Spend some time looking up blogs on error management in PowerShell until you understand how this is done.

    Try this:

    Try{
         $Connection.open()
    }
    Catch{
          Log-Results "$date`tSystem`tProcessing Failed`tCould not connect to $dbServer\$dbName`t$_"
          exit
    }
    
    Log-Results "$date`tSystem`tProcessing Started`tConnected to $dbServer\$dbName. Initializing Query Type: $queryType`t"
    

    The "Finally" block is not required since you are exiting.  Normally we almost never use "Finally" when the script is continuing. It is there only to cleanup prep for the call.  It is not an inflow statement and it is inefficient to use it unless you really understand whaty it is needed.


    ¯\_(ツ)_/¯

    Thursday, July 3, 2014 11:41 AM