我有這個洗掉 OneDrive 專案的腳本,但我只是想知道如何修改我的腳本,以便在找不到該專案時跳過該專案而不是停止執行。
現在我收到這個錯誤并且它停止執行。
Error: Item does not exist. It may have been deleted by another user.
我應該嘗試在我的 forEach 中捕獲嗎?這會阻止它停止執行嗎?
我首先在這里問它的原因是因為它洗掉了超過 400 萬個專案,我永遠不知道它什么時候會發生。
#Config Variables
$SiteURL = "https://companyname-my.sharepoint.com/personal/username/"
$ListName = "Documents"
$FolderServerRelativeURL = "/personal/sfdsf/Documents/PC-sdfd-sdf-01-Dec-0257"
Try {
#Connect to PnP Online
Connect-PnPOnline -Url $SiteURL -useWebLogin
$List = Get-PnPList $ListName
#Get All Items from Folder in Batch
$global:counter = 0;
$ListItems = Get-PnPListItem -List $ListName -PageSize 5000 -Fields ID, FileDirRef, FileRef -ScriptBlock `
{ Param($items) $global:counter = $items.Count; Write-Progress -PercentComplete ($global:Counter / ($List.ItemCount) * 100) -Activity `
"Getting Items from Folder '$FolderServerRelativeURL'" -Status "Getting Items $global:Counter of $($List.ItemCount)"; }
#Get List Items from the folder and Sort List Items based on Server Relative URL - Descending
$ItemsFromFolder = $ListItems | Where { $_.FieldValues["FileDirRef"] -match $FolderServerRelativeURL } | Select-Object @{Name = "ServerRelativeURL"; Expression = { $_.FieldValues.FileRef } }, ID | Sort-Object -Descending -Property ServerRelativeURL
Write-host "Total Number of Items Found in the Folder:"$ItemsFromFolder.count
#Delete List Items in Batch
$Batch = New-PnPBatch
ForEach ($Item in $ItemsFromFolder) {
Remove-PnPListItem -List $ListName -Identity $Item.ID -Batch $Batch
Write-host "Item Queued for deletion:"$Item.ServerRelativeURL
Invoke-PnPBatch -Batch $Batch -Details
}
Invoke-PnPBatch -Batch $Batch -Details
}
Catch {
write-host "Error: $($_.Exception.Message)" -foregroundcolor Red
}
uj5u.com熱心網友回復:
以達林的回答為基礎。我檢查了 Remove-PNPListItem 的在線檔案,它沒有 ErrorAction 引數,因此您需要使用 $ErrorActionPreference 變數來實際使 Catch 作業,因為它僅適用于終止錯誤。
$ErrorActionPreference = "Stop"
try {
Remove-PnPListItem -List $ListName -Identity $Item.ID -Batch $Batch
} catch {
#Write-Host "Missing $ListName"
}
$ErrorActionPreference = "Continue"
也就是說,我沒有安裝該軟體包,因此您可能只想嘗試將 -ErrorAction "STOP" 添加到您的 Remove-PnPListItem 并查看它是否有效,然后再嘗試使用首選項變數。
uj5u.com熱心網友回復:
記下引發錯誤的行號并將該行包裝在 try/catch 中。假設該行是 Remove-PnPListItem 命令,那么它看起來像這樣(如果您想查看缺少的內容,請取消注釋 Write-Host 并根據需要進行修改。):
try {
Remove-PnPListItem -List $ListName -Identity $Item.ID -Batch $Batch
} catch {
#Write-Host "Missing $ListName"
}
編輯:
這是關于“您想了解的有關例外的所有資訊”的頁面: https ://docs.microsoft.com/en-us/powershell/scripting/learn/deep-dives/everything-about-exceptions
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/434570.html
