首页 > 解决方案 > 终止 Powershell 功能出现任何错误

问题描述

我正在编写一个powershell脚本,其中有多个函数,如果中间出现任何错误,我想终止该函数而不转到下一个函数。

我的代码:


    function A
    { 
        Write-Host "A Block Started" -ForegroundColor Yellow
    }
    
    function B
    {    
        $master_key = facter -p dev_master_key
        $pwd = facter -p certificate_pwd
        $scriptPath = "$PSScriptRoot\script.sql"

Invoke-Sqlcmd -InputFile "$scriptPath"
    
    }
    
    function C
    { 
        Write-Host "C Block Started" -ForegroundColor Yellow
    }
    
    function D
    { 
        Write-Host "D Block Started" -ForegroundColor Yellow
    }
    
    $stamp = Get-Date -UFormat "%Y-%m-%d-%H-%M-%S"
    Start-Transcript "C:\temp\script-$ENV-$stamp.log"
    $start = Get-Date
    
    A
    B
    C
    D
    
    $end = Get-Date
    $totaltime = $end - $start
    Write-Host "`nTime Elapsed: $($totaltime.tostring("hh\:mm\:ss"))" -ForegroundColor red -BackgroundColor white
    Stop-Transcript

在函数中,我试图更改文件的内容然后触发脚本,如果脚本中出现任何错误,它将显示错误并移动到我不想要的下一个函数,我想在那里终止脚本本身。

标签: powershell

解决方案


$ErrorActionPreference = "Stop" 应该可以


推荐阅读