Forum Discussion

Redbaron99's avatar
Redbaron99
Copper Contributor
Mar 27, 2022
Solved

Restore all files but ones that already exist from the recycle bin using PowerShell

Hello, I have a client that I am working with that had a slight mix-up that lead to many duplicate files being created and then deleted (along with others that they need restored), there are 10,000...
  • Redbaron99's avatar
    Redbaron99
    Apr 06, 2022

    Thank you for your patience, and help. I was able to figure out the issue. The "(Get-Date)" string applies a time to it, thus, making it fail. I worked around it by using a date range instead. The following cmdlet solved the issue:

     

    Install-Module -Name PnP.PowerShell
    Import-Module PnP.PowerShell
    connect-pnponline -url *sharepoint site URL* -interactive

    $date1 = (Get-Date).date.AddDays(-5)
    $date2 = (Get-Date).date.AddDays(-6)

    Get-PnPRecycleBinItem | ForEach-Object {
    $dir = $_.DirName
    $title = $_.Title
    $path = "$dir/$title"
    $deletedDate = $_.DeletedDate

    $fileExists = Get-PnPFile -url $path -ErrorAction SilentlyContinue

    if ($fileExists) {
    Write-Host "$title exists"
    } else {
    Write-Host "$title doesn't exist"
    if ($deletedDate -gt $date2 -and $deletedDate -lt $date1) {
    Write-host "$title is equal to $date2 and will be restored"
    $_ | Restore-PnpRecycleBinItem -Force -ErrorAction SilentlyContinue
    } else {
    Write-Host "$title is not equal to $date2 and will not be restored"
    }
    }
    }

     

Resources