Question

I'm working on a general function to recover an item programatically from a recycle bin via Powershell and CSOM. This is what I have so far, it doesn't throw an error, but it doesn't recover the file either. test_word.docx is a word document I created and deleted, it does find it and output test_word.docx restored, but the file sits in the recycle bin still.

Am I missing something here?

$FileName = "test_word.docx"
$context = New-Object Microsoft.SharePoint.Client.ClientContext("https://tenant-my.sharepoint.com/personal/eric_alexander_domain_com")
$context.Credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($credential.UserName, $credential.Password)
$site = $context.Site
$recycleBinCollection = $site.RecycleBin
$context.Load($site)
$context.Load($recycleBinCollection)
$context.ExecuteQuery()

foreach($item in $recycleBinCollection){
        if($item.LeafName -eq $FileName){
           $item.Restore()
            Write-Host "$FileName restored"
            return
        }
}
Was it helpful?

Solution

You need to add $context.ExecuteQuery() at the end. Without it operations won't be executed on the server.

OTHER TIPS

You need to add $context.ExecuteQuery() also make sure you don't restore more than 30 files in a single ExecuteQuery otherwise you will get errors doing so.
Microsoft limited the Restore possibility to 30 files max (also timeouts might generate other errors).
That's why I always restore 20 by 20.

Tag the items to Restore or Delete

# Only Restore Files
if($recycleBinItem.ItemType -eq [Microsoft.SharePoint.Client.RecycleBinItemType]::File)
{
    $fullPath = $recycleBinItem.DirName
    $fullPath += "/"
    $fullPath += $recycleBinItem.Title
    "$fullPath will be restored"
    $recycleBinItem.Restore();
    $countModifications++;
    $countTotalModifications++;
}
# Delete Folders from RecycleBin
elseif($recycleBinItem.ItemType -eq [Microsoft.SharePoint.Client.RecycleBinItemType]::Folder)
{
    $fullPath = $recycleBinItem.DirName
    "$fullPath will be removed"
    $recycleBinItem.DeleteObject();
    $countModifications++;
    $countTotalModifications++;
}

Execute the modifications within the loop

if($countModifications -ge 20)
{
    "Executing $countModifications modifications"
    $siteContext.ExecuteQuery();
    "$countModifications modifications executed"
    $countModifications = 0;
}

Execute the modifications after the loop

if($countModifications -gt 0)
{
    "Remaining $countModifications modifications"
    $siteContext.ExecuteQuery()
    "Remaining $countModifications modifications executed"
    $countModifications = 0;
}

"$countTotalModifications modifications executed in total"
$siteCollection.Dispose()

References

https://gallery.technet.microsoft.com/office/How-to-get-recycle-bin-409cadb5

RecycleBinItem

RecycleBinItem.Restore

ClientContext

ClientContext.ExecuteQuery

Licensed under: CC-BY-SA with attribution
Not affiliated with sharepoint.stackexchange
scroll top