OneDrive for Business: Restore All Files and Folder from Recycle Bin using PowerShell

Requirement: Restore all deleted files and folders from OneDrive for business using PowerShell.

PowerShell to Restore All Deleted Items in OneDrive for Business

OneDrive for business stores all deleted items in the Recycle Bin. If you accidentally delete an item, you can restore the item from the Recycle Bin. Recovering deleted items from OneDrive for Business Recycle bin through the web browser interface is explained in another post: How to restore Files and folders from OneDrive? In this post, let’s see how to use PowerShell to restore all your deleted files and folders from the recycle bin.

Please note, You must have site collection administrator rights to the OneDrive site before proceeding with the restore.

#Parameters
$AdminCenterURL="https://crescent-admin.sharepoint.com"
$UserAccount = "Salaudeen@Crescent.com" #UPN

Try {
    #Connect to Admin Center
    Connect-PnPOnline -Url $AdminCenterURL -Interactive

    #Get onedrive site URL of the user
    $OneDriveURL = Get-PnPUserProfileProperty -Account $UserAccount | Select -ExpandProperty PersonalUrl

    If($OneDriveURL -ne $null)
    {
        #Connect to OneDrive site
        Connect-PnPOnline -Url $OneDriveURL -Interactive

        #Get All items in the recycle bin
        $RecycleBinItems = Get-PnPRecycleBinItem -RowLimit 500000

        #Check if there are any deleted items in recycle bins
        If($RecycleBinItems.count -eq 0) {
            Write-host "No Items found in the recycle bin!" -f Yellow
            Break
        }

        #Restore all items from the recycle bin
        $RecycleBinItems = Get-PnPRecycleBinItem -RowLimit 500000
        ForEach($Item in $RecycleBinItems)
        {
            #Get the Original location of the deleted file or folder
            $OriginalLocation = "/"+$Item.DirName+"/"+$Item.LeafName
            If($Item.ItemType -eq "File")
            {
                $OriginalItem = Get-PnPFile -Url $OriginalLocation -AsListItem -ErrorAction SilentlyContinue
            }
            Else #Folder
            {
                $OriginalItem = Get-PnPFolder -Url $OriginalLocation -ErrorAction SilentlyContinue
            }
            #Check if the item exists in the original location
            If($OriginalItem -eq $null)
            { 
                #Restore the item
                Restore-PnPRecycleBinItem -Identity $Item -Force
                Write-host "Restored Item '$($Item.LeafName)' to '$($Item.DirName)'" -f Green
            }
            Else
            {
                Write-Host "A file or folder with this name $($Item.LeafName) already exists in '$($Item.DirName)', Skipping.."  -f Yellow
            }
        }
    }
    Else
    {
        Write-host "OneDrive site for the user doesn't exist!" -f Yellow
    }
}
Catch {
    Write-host "Error: $($_.Exception.Message)" -foregroundcolor Red
}

Related post: Restore Deleted Files from Recycle Bin in SharePoint Online using PowerShell

Salaudeen Rajack

Salaudeen Rajack - Information Technology Expert with Two-decades of hands-on experience, specializing in SharePoint, PowerShell, Microsoft 365, and related products. He has held various positions including SharePoint Architect, Administrator, Developer and consultant, has helped many organizations to implement and optimize SharePoint solutions. Known for his deep technical expertise, He's passionate about sharing the knowledge and insights to help others, through the real-world articles!

One thought on “OneDrive for Business: Restore All Files and Folder from Recycle Bin using PowerShell

  • Hey Salaudeen,

    Just further to the above, please find my working script below which allows you to do a bulk OneDrive for Business recycle bin restore via users in a CSV file and gives allowance to restore back to x amount of days:

    The script calls a CSV file with your Office365 users and does a recursive loop to check each user’s recycle bin and restore it back to x amount of days back. Note the CSV file will need to have a header named ‘Owner’ to specify all the user accounts which will be called in the ‘ for each’ section at the bottom of the script.

    Also should the global admin account have MFA on it, create an app password (as per the $Password parameter) to allow the recursive pass on each OneDrive account OR disable MFA until the script is completed.

    Note in the $restoreDate parameter, this allows you to specify how many days back you want to restore the Recycle Bin contents from.

    —————————-

    #Parameters
    $AdminCenterURL=”https://contoso-admin.sharepoint.com”
    $UserName=”admin@contoso.onmicrosoft.com”
    $Password=””

    $SecurePassword = ConvertTo-SecureString -String $Password -AsPlainText -Force
    $Cred = New-Object -TypeName System.Management.Automation.PSCredential -argumentlist $UserName, $SecurePassword

    #Connect to Admin Center
    Connect-PnPOnline -Url $AdminCenterURL -Credentials $Cred

    function OneDriveRestore ($UserAccount){
    Try {

    #Get User OneDrive site URL
    $OneDriveURL = Get-PnPUserProfileProperty -Account $UserAccount | Select -ExpandProperty PersonalUrl

    If($OneDriveURL -ne $null)
    {
    #Connect to OneDrive site
    Connect-PnPOnline -Url $OneDriveURL -Credentials $Cred

    #Get All items in the recycle bin
    $RecycleBinItems = Get-PnPRecycleBinItem -RowLimit 500000

    #Check if there are any deleted items in recycle bins
    If($RecycleBinItems.count -eq 0) {
    Write-host “No Items found in the recycle bin!” -f Yellow
    #Break
    }

    #Restore all items from the recycle bin
    $restoreDate = (Get-Date).AddDays(-10)
    $RecycleBinItems = Get-PnPRecycleBinItem -RowLimit 500000 -Firststage | where {($_.DeletedDate -gt $restoreDate)}

    ForEach($Item in $RecycleBinItems)
    {
    #Get the Original location of the deleted file or folder
    $OriginalLocation = “/”+$Item.DirName+”/”+$Item.LeafName
    If($Item.ItemType -eq “File”)
    {
    $OriginalItem = Get-PnPFile -Url $OriginalLocation -AsListItem -ErrorAction SilentlyContinue
    }
    Else #Folder
    {
    $OriginalItem = Get-PnPFolder -Url $OriginalLocation -ErrorAction SilentlyContinue
    }
    #Check if the item exists in the original location
    If($OriginalItem -eq $null)
    {
    #Restore the item

    Restore-PnPRecycleBinItem -Identity $Item -Force
    Write-host “Restored Item ‘$($Item.LeafName)’ to ‘$($Item.DirName)'” -f Green
    }
    Else
    {
    Write-Host “A file or folder with this name $($Item.LeafName) already exists in ‘$($Item.DirName)’, Skipping..” -f Yellow
    }
    }
    }
    Else
    {
    Write-host “OneDrive site for the user doesn’t exist!” -f Yellow
    }
    }
    Catch {
    Write-host “Error: $($_.Exception.Message)” -foregroundcolor Red
    }

    }

    #Connect-PnPOnline -Url $AdminCenterURL -Interactive

    # Import the CSV file
    $data = Import-Csv -Path “C:\Temp\OneDriveUsers.csv”

    foreach ($row in $data) {
    # Check if the ‘Name’ column has a value
    if ($row.Owner) {
    Write-Host “Owner: $($row.Owner)”
    OneDriveRestore -UserAccount $row.Owner
    } else {
    Write-Host “Owner value is empty or null.”
    }
    }

    Reply

Leave a Reply

Your email address will not be published. Required fields are marked *