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"
}
}
}
You're welcome!
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"
}
}
}