Terminating a script in PowerShell

前端 未结 10 1729
走了就别回头了
走了就别回头了 2020-11-28 01:02

I\'ve been looking for a way to terminate a PowerShell (PS1) script when an unrecoverable error occurs within a function. For example:

function foo() {
    #         


        
相关标签:
10条回答
  • 2020-11-28 01:15

    Exit will exit PowerShell too. If you wish to "break" out of just the current function or script - use Break :)

    If ($Breakout -eq $true)
    {
         Write-Host "Break Out!"
         Break
    }
    ElseIf ($Breakout -eq $false)
    {
         Write-Host "No Breakout for you!"
    }
    Else
    {
        Write-Host "Breakout wasn't defined..."
    }
    
    0 讨论(0)
  • 2020-11-28 01:15

    I used this for a reruning of a program. I don't know if it would help, but it is a simple if statement requiring only two different entry's. It worked in powershell for me.

    $rerun = Read-Host "Rerun report (y/n)?"
    
    if($rerun -eq "y") { Show-MemoryReport }
    if($rerun -eq "n") { Exit }
    

    Don't know if this helps, but i believe this would be along the lines of terminating a program after you have run it. However in this case, every defined input requires a listed and categorized output. You could also have the exit call up a new prompt line and terminate the program that way.

    0 讨论(0)
  • 2020-11-28 01:19

    Throwing an exception will be good especially if you want to clarify the error reason:

    throw "Error Message"
    

    This will generate a terminating error.

    0 讨论(0)
  • 2020-11-28 01:21

    Write-Error is for non-terminating errors and throw is for terminating errors

    The Write-Error cmdlet declares a non-terminating error. By default, errors are sent in the error stream to the host program to be displayed, along with output.

    Non-terminating errors write an error to the error stream, but they do not stop command processing. If a non-terminating error is declared on one item in a collection of input items, the command continues to process the other items in the collection.

    To declare a terminating error, use the Throw keyword. For more information, see about_Throw (http://go.microsoft.com/fwlink/?LinkID=145153).

    0 讨论(0)
提交回复
热议问题