【问题标题】:Powershell code not exiting after try catch block尝试捕获块后Powershell代码未退出
【发布时间】:2020-11-11 17:26:53
【问题描述】:

我有一个代码,可以从 SharePoint 下载文件,对其进行编辑,然后将其上传回 SharePoint,最后发送一封确认电子邮件。我有每个任务的功能。代码运行良好。

但是,我想为某些用户在 SharePoint 中打开文件时的条件添加错误异常,显示错误消息和退出代码。我遇到的问题是即使出现异常代码也会继续运行。在下面的代码中,即使 getSharePointFile 函数失败,也会调用 sendMail 函数。

我已经尝试过 $ErrorActionPreference = "Stop" 但是这样,catch 块没有执行,我的自定义错误消息框也没有显示。提前致谢。

以下是相关代码:

function getSharePointFile {
    Connect-PnPOnline $SharepointURL -UseWebLogin
    Get-PnPFile -Url $fileRelativeURL -Path $localFilePath -FileName $fileName -AsFile -Force 
}

function runCatch {
    $showMessage = [System.Windows.Forms.MessageBox]::Show($_)
    exit
}

try {getSharePointFile}   
catch{runCatch}

try {updateAuditResults}   
catch{runCatch}

try {uploadToSharePoint}   
catch{runCatch}

try {sendMail}   
catch{runCatch}

【问题讨论】:

    标签: powershell try-catch exit


    【解决方案1】:

    两个问题:

    首先,您有四个独立的 try catch 块,其中一个处理的错误不会影响其他块。

    试试这样的:

    try {
      getSharePointFile
      updateAuditResults
      uploadToSharePoint
      sendMail
    }   
    catch{runCatch}
    

    产生错误的第一行将结束这批命令并跳转到catch块。将跳过该批次的其余部分。

    您可能遇到的第二个问题是,并非所有 PowerShell cmdlet 在失败时都会返回错误。你需要测试你的来验证。有些只会显示错误文本并继续。

    更多信息在这里:https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_try_catch_finally

    【讨论】:

      【解决方案2】:

      正如@Mike Smith 所说,使用您提供的代码,将您的函数调用合并到一个try catch 块中似乎更好。

      根据您的 PowerShell 版本,您还需要添加 -ErrorAction Stop 参数以将错误捕获到 catch 块中(为 cmdlet 添加它,而不是函数调用)

      function getSharePointFile {
         Connect-PnPOnline $SharepointURL -UseWebLogin -ErrorAction Stop
         Get-PnPFile -Url $fileRelativeURL -Path $localFilePath -FileName $fileName -AsFile -Force -ErrorAction Stop
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-02-21
        • 2014-01-28
        • 2011-08-23
        • 2018-01-10
        • 1970-01-01
        • 2020-08-12
        相关资源
        最近更新 更多