当前位置:网站首页 > 更多 > 玩电脑 > 正文

[玩转系统] SharePoint Online:在 PowerShell 中使用 Try Catch 进行错误处理

作者:精品下载站 日期:2024-12-14 15:32:06 浏览:13 分类:玩电脑

SharePoint Online:在 PowerShell 中使用 Try Catch 进行错误处理


编写 PowerShell 脚本的最佳实践之一是处理潜在的错误,以确保出现问题时脚本的顺利执行。谁能保证一个脚本在不同的环境下每次都能正确运行?使用类似于 .NET 框架的 try-catch 块可以轻松处理 PowerShell 中的错误。当“Try”块内的脚本出现问题时,脚本流程将转移到“Catch”块来处理错误。

尝试在 PowerShell SharePoint Online 中进行 Catch

以下是有关在 PowerShell for SharePoint Online 中 Try-Catch 错误处理如何工作的基本示例:


Try {
    Connect-SPOService -url "https://crescent-admin.sharepoint.com"
}
Catch {
    write-host -f Red "Error:" $_.Exception.Message
}

[玩转系统] SharePoint Online:在 PowerShell 中使用 Try Catch 进行错误处理

在此示例中,如果在执行 try 块中的代码时抛出异常,脚本将跳转到 catch 块,其中将使用Write-Host cmdlet。同样,以下是如何在 CSOM 脚本中使用 Try-Catch 来检查列表是否存在:


#Load SharePoint CSOM Assemblies
Add-Type -Path "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\ISAPI\Microsoft.SharePoint.Client.dll"
Add-Type -Path "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\ISAPI\Microsoft.SharePoint.Client.Runtime.dll"
 
#Function to check if a list or document library exists
Function Check-SPOListExists([Microsoft.SharePoint.Client.ClientContext]$Ctx, [String]$ListName)
{
    Try {
        $List = $Ctx.Web.Lists.GetByTitle($ListName)
        $Ctx.Load($List)
        $Ctx.ExecuteQuery()
        Return $True
    }
    Catch [Exception] {
        Write-host $_.Exception.Message -f Red
        Return $False
     }
}
    
#Config Parameters
$SiteUrl = "https://crescent.sharepoint.com/sites/projects"
$ListName="Project Documents"
 
#Get Credentials to connect
$Cred= Get-Credential
   
#Set up the context
$Ctx = New-Object Microsoft.SharePoint.Client.ClientContext($SiteUrl)
$Ctx.Credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($Cred.Username, $Cred.Password)
    
#Call the function to Check List Exists
Check-SPOListExists -Ctx $Ctx -ListName $ListName

您可以对错误消息执行任何您想要的操作,例如在屏幕上显示自定义警告而不是错误!然而,并不是所有异常都可以通过 Try-Catch 块处理!让我们运行以下脚本:


$SiteURL = "https://crescent.sharepoint.com/sites/marketing"
$SubSiteURL = "2010"
  
#Connect to PnP Online
Connect-PnPOnline -Url $SiteURL -Credentials (Get-Credential)

Try { 
    #Get a subsite
    $Web = Get-PnPWeb -Identity $SubSiteURL
}
Catch {
    Write-host "Error:"$_.Exception.Message -f Red
}

如果运行此脚本,您将得到:

[玩转系统] SharePoint Online:在 PowerShell 中使用 Try Catch 进行错误处理

虽然我们在脚本中使用了 Try-Catch 块,但是您可以发现 catch 块没有处理错误!这是因为: PowerShell 中有两种类型的错误。

  1. 终止错误
  2. 非终止错误。

终止错误是指将停止功能或操作的错误。非终止错误允许 PowerShell 继续运行,通常来自 cmdlet 或其他托管情况。默认情况下,Try-Catch 块只能捕获终止错误!为了能够捕获非终止错误,您应该设置 cmdlet 的 $ErrorActionPreference 变量或设置 ErrorAction 参数。

尝试使用多个 Catch 块


try {
	 //Some Script
}
catch [Exception 1],[Exception 2] {
    //Action something
}
catch {
    //Generic error
    Write-host $_.Exception.Message
}

使用“ErrorAction”参数:

每个 PowerShell cmdlet 都支持 ErrorAction 开关。通过在 cmdlet 末尾指定“-ErrorAction Stop”,可以确保它抛出的任何错误都被视为终止,并且可以被 catch 块捕获。


Try { 
    #Get a subsite
    $Web = Get-PnPWeb -Identity $SubSiteURL -ErrorAction Stop
}
Catch {
    Write-host "Subsite doesn't Exist!" -f Red
}

[玩转系统] SharePoint Online:在 PowerShell 中使用 Try Catch 进行错误处理

这是另一个例子:


#Parameters
$SiteURL = "https://crescent.sharepoint.com/sites/Retail"
$FileURL = "/sites/Retail/Shared Documents/2019/SiteAdmins-UNKNOWN.csv"

Try {
    #Connect to SharePoint admin site
    Connect-PnPOnline -Url $SiteURL -Interactive

    #Get the File
    $File = Get-PnPFile -Url $FileURL -AsFileObject -ErrorAction Stop
    Write-host $File.Length
}
Catch {
    write-host "Error: $($_.Exception.Message)" -foregroundcolor Red
}

使用 $ErrorActionPreference 变量

还可以使用 ErrorActionPreference 变量将所有错误视为终止。如何捕获非终止错误?基本上,您告诉 PowerShell 将其视为终止。您可以通过设置 - $ErrorActionPreference =“Stop”将所有错误转为终止,然后将其重置回“Continue”。这是一个例子:


#Config Variables
$SiteURL = "https://crescent.sharepoint.com/sites/marketing"
$SubSiteURL = "2010"
  
#Connect to PnP Online
Connect-PnPOnline -Url $SiteURL -Interactive

Try {
    #Set Error Preference variable to Stop
    $ErrorActionPreference = "Stop" 
    #Get a subsite
    $Web = Get-PnPWeb -Identity $SubSiteURL
}
Catch {
    Write-host "Subsite doesn't Exist!" -f Red
}
Finally {
    #Rest Error Preference to Default
    $ErrorActionPreference = "Continue"
}

“Finally”块每次都会运行,无论是否有错误。通过这种方式,我们可以执行无论操作成功还是失败都必须执行的操作。

$ErrorActionPreference 变量指定为响应发生的错误而采取的操作。支持以下值:

  • SilentlyContinue - 不显示错误消息继续执行后续脚本。它可以抑制错误输出到 shell 中。
  • 继续 -(默认)显示错误消息并尝试继续执行后续命令。
  • 查询 - 提示用户是继续还是终止操作
  • 停止 - 因错误而终止操作。
  • Break - 当发生错误或引发异常时进入调试器。
  • 忽略:抑制错误消息并继续执行命令。忽略值旨在供每个命令使用,而不是用作保存的首选项。 Ignore 不是 $ErrorActionPreference 变量的有效值。

您需要 登录账户 后才能发表评论

取消回复欢迎 发表评论:

关灯