Forum Discussion
Restore all files but ones that already exist from the recycle bin using PowerShell
- 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"
}
}
}
Hello,
I assume you are meaning from SharePoint Recycle bin.
I quickly threw together a site, files, and this script and it worked when I deleted files and restored them. I included some resources as well so you could make a better/cleaner script for your need.
connect-pnponline -url https://your.sharepoint.com/ -interactive
$recycleBin = Get-PnPRecycleBinItem
$recycleBin | ForEach-Object {
$dir = $_.DirName
$title = $_.Title
$path = "$dir/$title"
$fileExists = Get-PnPFile -url $path -ErrorAction SilentlyContinue
if ($fileExists) {
Write-Host "$title exists"
} else {
Write-Host "$title Restoring"
$_ | Restore-PnpRecycleBinItem -Force
}
}
Read-Host "Done"
Sources
https://www.sharepointdiary.com/2019/02/sharepoint-online-powershell-to-restore-deleted-items-from-recycle-bin.html#:~:text=SharePoint%20Online%3A%20Restore%20Deleted%20Items%20from%20Recycle%20Bin,to%20restore%20and%20click%20the%20%22Restore%20Selection%22%20link.
https://github.com/joseinazusa/powershell-recursive-folder-restore/blob/master/recursive-recyclebin-restore.ps1
https://pnp.github.io/powershell/cmdlets/Restore-PnPRecycleBinItem.html
https://pnp.github.io/powershell/cmdlets/Get-PnPRecycleBinItem.html
- Redbaron99Mar 28, 2022Copper ContributorThank you so much, I’ll mess around with it for a bit. Am still learning PowerShell so thank you for the resources as well!
- LeaviiMar 28, 2022Brass ContributorOf course. Always glad to help. Let us know how it goes, eh? 😄
- Redbaron99Mar 28, 2022Copper ContributorAfter messing with it, it does seem to be working, I’m giving it a couple of days to test the date filter a bit more. Thank you again.