Created
March 6, 2025 21:58
-
-
Save joerodgers/d72ffefa25fef9dd13d7bac86283e9ea to your computer and use it in GitHub Desktop.
Restores a list of sites in the recycle bin by SiteId
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#requires -modules "pnp.powershell" | |
# requires SharePoint > Application > Sites.FullControl.All | |
Connect-PnPOnline -Url "https://$env:CDX_TENANT-admin.sharepoint.com" ` | |
-ClientId $env:CDX_CLIENTID ` | |
-Thumbprint $env:CDX_THUMBPRINT ` | |
-Tenant $env:CDX_TENANTID ` | |
-ErrorAction Stop | |
$ids = "f070b698-2c88-4244-a488-4d71f84e91b3", "98b2c6d2-e402-4c3e-a6b1-3ad33fe6525d", "9c2b4224-c93b-45c0-a291-9450dfb9f606", "cca1751f-9f72-4fba-a957-c6df8d3fa7f0", "c5fe53da-2e59-4dee-98c4-95c52a60cdb8" | |
# restore all the matching sites in the recycle bin | |
$deletedSites = Get-PnPTenantDeletedSite -Limit 100000 | |
if( $deletedSites.Count -eq 0 ) | |
{ | |
Write-Host "[$(Get-Date)] - No sites found in the recycle bin." | |
return | |
} | |
# find all the matching siteIds for sites in the recycle bin using the provided SiteId list | |
$sitesIds = Compare-Object -ReferenceObject $ids -DifferenceObject $deletedSites.SiteId -IncludeEqual | Where-Object -Property SideIndicator -eq "==" | Select-Object -ExpandProperty InputObject | |
$results = foreach( $siteId in $sitesIds ) | |
{ | |
$deletedSite = $deletedSites | Where-Object -Property SiteId -eq $siteId | |
Write-Host "[$(Get-Date)] - Restoring Site: $($deletedSite.Url)" | |
Restore-PnPTenantSite -Identity $deletedSite.Url -NoWait -Force | |
[PSCustomObject] @{ | |
SiteId = $siteId | |
SiteUrl = $deletedSite.Url | |
State = "Restored" | |
} | |
} | |
# check if any of the sites have already been restored | |
# find all the matching siteIds for sites NOT in the recycle bin using the provided SiteId list | |
$sitesIds = Compare-Object -ReferenceObject $ids -DifferenceObject $deletedSites.SiteId | Where-Object -Property SideIndicator -eq "<=" | Select-Object -ExpandProperty InputObject | |
$results += foreach( $siteId in $sitesIds ) | |
{ | |
$url = "/_api/Microsoft.Online.SharePoint.TenantAdministration.Tenant/sites('{0}')" -f $siteId | |
$response = Invoke-PnPSPRestMethod -Method Get -Url $url -ErrorAction SilentlyContinue | |
if( $null -ne $response ) | |
{ | |
[PSCustomObject] @{ | |
SiteId = $siteId | |
SiteUrl = $response.Url | |
State = "Active" | |
} | |
} | |
else | |
{ | |
[PSCustomObject] @{ | |
SiteId = $siteId | |
SiteUrl = "" | |
State = "Not found" | |
} | |
} | |
} | |
# log results | |
$results | Sort-Object -Property SiteId | Export-Csv -Path "RestoreResults.csv" -NoTypeInformation |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment