'Skip item when not found in PowerShell

I've this script that delete OneDrive item but I'm just wondering how can I modify my script so that when the item is not found then just skip for that item instead of stop executing.

Right now I'm getting this error and it stop executing.

Error: Item does not exist. It may have been deleted by another user.

Should I do try catch inside my forEach?. Will that prevent it from stop executing?.

The reason I'm asking it here first is because it deleting over 4million items and I'll never know when it will occur.

#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
}



Solution 1:[1]

Take note of the line number throwing the error and wrap the line in a try/catch. Assuming the line turns out to be the Remove-PnPListItem command, then it would look like this (If you want to see what is missing, then uncomment the Write-Host and modify it as you desire.):

try {
    Remove-PnPListItem -List $ListName -Identity $Item.ID  -Batch $Batch
} catch {
    #Write-Host "Missing $ListName"
}

EDIT:

Here is a page on "Everything you wanted to know about exceptions": https://docs.microsoft.com/en-us/powershell/scripting/learn/deep-dives/everything-about-exceptions

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1