Restore Files from Recycle Bin

Below script to get the items filter by the deleted by and restore it.


$logfile = "C:\Logs_$(get-date -format `"yyyyMMdd_hhmmsstt`").log"
New-Item $Logfile
function ConnectSharePointOnline {
    param (
        [string]$siteUrl = "$(Read-Host 'Enter the Site Collection URL.')"
    )
    $siteUrl
    $credentials = Get-Credential
    try{
        Connect-PnPOnline -Url $siteUrl -Credentials $credentials
    $UserEmail = Read-Host -Prompt "Enter User email Address to recover deleted files from recycle bin"
    LogWrite "Need to restore files for User Title : $UserEmail"
    $user = Get-PnPUser| Where-Object{$_.Email -eq $UserEmail}
    if($null -ne $user){
        $files = Get-PnPRecycleBinItem | Select-Object * |Where-Object {$_.DeletedByName -eq $user.Title}
        if($files.Count -ge 0){
            $totalCount = $files.Count
            LogWrite "Total Files need to restore : $totalCount"
            $files | ForEach-Object{
                try {
                 Restore-PnPRecycleBinItem -Identity  $_.Id.ToString() -Force
                }
                catch {
                    LogWrite $_.Message 
                }
            }
        }
        else {
            LogWrite "No files are found"
        }
    }
    else {
        LogWrite "User does not found with email address " + ($UserEmail)
    }
}
    catch {
        LogWrite $_
    }
}
function LogWrite
{
   Param ([string]$logstring)
   Add-content $Logfile -value $logstring
}
ConnectSharePointOnline

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.