Jump to content

Powershell Script for restoring items from the recycle bin in Sharepoint


Recommended Posts

Posted

Hi Guys having an issue with this script that was made with ChatGPT keeps coming back with this error anyone have any ideas?

 

# First, let's output the PnP PowerShell version for debugging$module = Install-Module PnP.PowerShell -ForceWrite-Host "PnP PowerShell version installed: $($module.Version)" # Clear any existing connectionstry { Disconnect-PnPOnline } catch { } # Try to connect using the basic methodtry {    Write-Host "Attempting to connect to SharePoint..."    try {        # First attempt - modern authentication        Connect-PnPOnline -Url "[color=#000000]User site will be here [/color]" -Interactive    } catch {        Write-Host "Modern auth failed, trying alternative method..." -ForegroundColor Yellow        Connect-PnPOnline -Url "and also here user site" -UseWebLogin    }    # Test the connection    $web = Get-PnPWeb    Write-Host "Connected to site: $($web.Title)" -ForegroundColor Green        # Store the site URL for later use    $siteUrl = "https://carltondigbyschool.sharepoint.com/sites/CDSStaff"     # Proceed with recycle bin operations    $deletionDate = "2025-01-03" # Change this to your target date    $targetDate = [DateTime]::ParseExact($deletionDate, "yyyy-MM-dd", $null).Date        Write-Host "Retrieving recycle bin items..."    $recycledItems = @()        # Get recycle bin items using smaller batches    $batchSize = 100    $firstRow = 0        do {        Write-Host "Retrieving items $firstRow to $($firstRow + $batchSize)..." -ForegroundColor Yellow        $batch = Get-PnPRecycleBinItem -RowLimit $batchSize | Select-Object -Skip $firstRow -First $batchSize                if ($batch) {            $filteredBatch = $batch | Where-Object {                 $_.DeletedDate.Date -eq $targetDate            }            $recycledItems += $filteredBatch            Write-Host "Processed $($firstRow + $batch.Count) items..." -ForegroundColor Yellow        }                $firstRow += $batchSize        Start-Sleep -Milliseconds 500            } while ($batch -and $batch.Count -eq $batchSize)    Write-Host "Found $($recycledItems.Count) items deleted on $deletionDate"    $recycledItems | ForEach-Object {        Write-Host "- $($_.Title) (Deleted by: $($_.DeletedByEmail))"        Write-Host "  ID: $($_.Id)"    }     if ($recycledItems.Count -gt 0) {        $confirmation = Read-Host "Do you want to restore these items? (Y/N)"        if ($confirmation -eq 'Y') {            foreach ($item in $recycledItems) {                try {                    Write-Host "Attempting to restore: $($item.Title)" -ForegroundColor Yellow                    Write-Host "Item ID: $($item.Id)" -ForegroundColor Yellow                                        # Construct the full REST API URL                    $restEndpoint = "$siteUrl/_api/web/RecycleBin('$($item.Id)')/Restore()"                    Write-Host "Using REST endpoint: $restEndpoint" -ForegroundColor Yellow                                        # Execute REST POST request with proper headers                    $response = Invoke-PnPSPRestMethod -Method Post -Url $restEndpoint -Headers @{                        "Accept" = "application/json;odata=verbose"                        "Content-Type" = "application/json;odata=verbose"                    }                                        Write-Host "Successfully restored: $($item.Title)" -ForegroundColor Green                    Start-Sleep -Seconds 1                }                catch {                    Write-Host "Failed to restore: $($item.Title)" -ForegroundColor Red                    Write-Host "Error: $_" -ForegroundColor Red                                        # Try alternative REST endpoint for second stage recycle bin                    try {                        Write-Host "Trying second stage recycle bin..." -ForegroundColor Yellow                        $secondStageEndpoint = "$siteUrl/_api/web/RecycleBin2('$($item.Id)')/Restore()"                        $response = Invoke-PnPSPRestMethod -Method Post -Url $secondStageEndpoint -Headers @{                            "Accept" = "application/json;odata=verbose"                            "Content-Type" = "application/json;odata=verbose"                        }                        Write-Host "Successfully restored from second stage: $($item.Title)" -ForegroundColor Green                    }                    catch {                        Write-Host "Failed to restore from second stage recycle bin" -ForegroundColor Red                        Write-Host "Error: $_" -ForegroundColor Red                        Write-Host "`nPlease try restoring manually:" -ForegroundColor Yellow                        Write-Host "1. Go to: $siteUrl" -ForegroundColor Yellow                        Write-Host "2. Click the Settings gear icon" -ForegroundColor Yellow                        Write-Host "3. Click 'Site contents'" -ForegroundColor Yellow                        Write-Host "4. Click 'Recycle bin' in the top right" -ForegroundColor Yellow                        Write-Host "5. Find the file: $($item.Title)" -ForegroundColor Yellow                        Write-Host "6. Select the file and click 'Restore'" -ForegroundColor Yellow                    }                }            }        }    }}catch {    Write-Host "Error occurred: $_" -ForegroundColor Red    Write-Host "`nTroubleshooting steps:" -ForegroundColor Yellow    Write-Host "1. Try running PowerShell as Administrator" -ForegroundColor Yellow    Write-Host "2. Make sure you have the correct SharePoint URL" -ForegroundColor Yellow    Write-Host "3. Verify you have site collection admin rights" -ForegroundColor Yellow    Write-Host "4. Try restoring the item manually from SharePoint if the script fails" -ForegroundColor Yellow}finally {    # Always disconnect at the end    try { Disconnect-PnPOnline } catch { }}

 

 

It pulls the file from sharepoint but comes up with this error?

 

Screenshot 2025-01-09 155245.png

 

Any help would be appreciated!!! Thanks Guys!

  • 3 months later...
Posted

Super late reply but give this a go: 

 



# Install the PnP PowerShell module
$module = Install-Module PnP.PowerShell -Force
Write-Host "PnP PowerShell version installed: $($module.Version)"

# Disconnect any existing connection
try { Disconnect-PnPOnline } catch { }

# Try to connect to SharePoint
try {
    Write-Host "Attempting to connect to SharePoint..."

    try {
        # First attempt - modern authentication
        Connect-PnPOnline -Url "https://carltondigbyschool.sharepoint.com/sites/CDSStaff" -Interactive
    } catch {
        Write-Host "Modern auth failed, trying alternative method..." -ForegroundColor Yellow
        Connect-PnPOnline -Url "https://carltondigbyschool.sharepoint.com/sites/CDSStaff" -UseWebLogin
    }

    # Test the connection
    $web = Get-PnPWeb
    Write-Host "Connected to site: $($web.Title)" -ForegroundColor Green

    $siteUrl = "https://carltondigbyschool.sharepoint.com/sites/CDSStaff"
    $deletionDate = "2025-01-03"  # Change this to your target date
    $targetDate = [DateTime]::ParseExact($deletionDate, "yyyy-MM-dd", $null).Date

    Write-Host "Retrieving recycle bin items..."
    $recycledItems = @()
    $batchSize = 100
    $firstRow = 0

    do {
        Write-Host "Retrieving items $firstRow to $($firstRow + $batchSize)..." -ForegroundColor Yellow
        $batch = Get-PnPRecycleBinItem -RowLimit $batchSize | Select-Object -Skip $firstRow -First $batchSize

        if ($batch) {
            $filteredBatch = $batch | Where-Object { $_.DeletedDate.Date -eq $targetDate }
            $recycledItems += $filteredBatch
            Write-Host "Processed $($firstRow + $batch.Count) items..." -ForegroundColor Yellow
        }

        $firstRow += $batchSize
        Start-Sleep -Milliseconds 500
    } while ($batch -and $batch.Count -eq $batchSize)

    Write-Host "Found $($recycledItems.Count) items deleted on $deletionDate"
    $recycledItems | ForEach-Object {
        Write-Host "- $($_.Title) (Deleted by: $($_.DeletedByEmail))"
        Write-Host "  ID: $($_.Id)"
    }

    if ($recycledItems.Count -gt 0) {
        $confirmation = Read-Host "Do you want to restore these items? (Y/N)"
        if ($confirmation -eq 'Y') {
            foreach ($item in $recycledItems) {
                try {
                    Write-Host "Attempting to restore: $($item.Title)" -ForegroundColor Yellow
                    Write-Host "Item ID: $($item.Id)" -ForegroundColor Yellow

                    $restEndpoint = "$siteUrl/_api/web/RecycleBin('$($item.Id)')/Restore()"
                    Write-Host "Using REST endpoint: $restEndpoint" -ForegroundColor Yellow

                    # REST call using correct parameter
                    $response = Invoke-PnPSPRestMethod -Method Post -Url $restEndpoint -ContentType "application/json;odata=verbose"
                    Write-Host "Successfully restored: $($item.Title)" -ForegroundColor Green
                    Start-Sleep -Seconds 1
                } catch {
                    Write-Host "Failed to restore: $($item.Title)" -ForegroundColor Red
                    Write-Host "Error: $_" -ForegroundColor Red

                    # Try second stage recycle bin
                    try {
                        Write-Host "Trying second stage recycle bin..." -ForegroundColor Yellow
                        $secondStageEndpoint = "$siteUrl/_api/web/RecycleBin2('$($item.Id)')/Restore()"
                        $response = Invoke-PnPSPRestMethod -Method Post -Url $secondStageEndpoint -ContentType "application/json;odata=verbose"
                        Write-Host "Successfully restored from second stage: $($item.Title)" -ForegroundColor Green
                    } catch {
                        Write-Host "Failed to restore from second stage recycle bin" -ForegroundColor Red
                        Write-Host "Error: $_" -ForegroundColor Red
                        Write-Host "`nPlease try restoring manually:" -ForegroundColor Yellow
                        Write-Host "1. Go to: $siteUrl" -ForegroundColor Yellow
                        Write-Host "2. Click the Settings gear icon" -ForegroundColor Yellow
                        Write-Host "3. Click 'Site contents'" -ForegroundColor Yellow
                        Write-Host "4. Click 'Recycle bin' in the top right" -ForegroundColor Yellow
                        Write-Host "5. Find the file: $($item.Title)" -ForegroundColor Yellow
                        Write-Host "6. Select the file and click 'Restore'" -ForegroundColor Yellow
                    }
                }
            }
        }
    }

} catch {
    Write-Host "Error occurred: $_" -ForegroundColor Red
    Write-Host "`nTroubleshooting steps:" -ForegroundColor Yellow
    Write-Host "1. Try running PowerShell as Administrator"
    Write-Host "2. Make sure you have the correct SharePoint URL"
    Write-Host "3. Verify you have site collection admin rights"
    Write-Host "4. Try restoring manually from SharePoint if the script fails"
} finally {
    try { Disconnect-PnPOnline } catch { }
}

 

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now



×
×
  • Create New...