簡體   English   中英

在 try catch 塊后 Powershell 代碼未退出

[英]Powershell code not exiting after try catch block

我有一個代碼,可以從 SharePoint 下載文件,對其進行編輯,然后將其上傳回 SharePoint,最后發送一封確認電子郵件。 我有每個任務的功能。 該代碼工作正常。

但是,如果某個用戶在 SharePoint 中打開文件,我想為某個條件添加錯誤異常,顯示錯誤消息和退出代碼。 我遇到的問題是即使出現異常代碼也會繼續運行。 在下面的代碼中,即使 getSharePointFile 函數失敗,也會調用 sendMail 函數。

我試過 $ErrorActionPreference = "Stop" 但是這樣,catch 塊沒有執行,我的自定義錯誤 MessageBox 也沒有顯示。 提前致謝。

這是相關的代碼:

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}

兩個問題:

首先,您有四個獨立的 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

正如@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
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM