diff --git a/SharePointOnline/ListAllSitesPnP.ps1 b/SharePointOnline/ListAllSitesPnP.ps1 new file mode 100644 index 0000000..ef03580 --- /dev/null +++ b/SharePointOnline/ListAllSitesPnP.ps1 @@ -0,0 +1,64 @@ +[CmdletBinding()] +param( + [Parameter(Mandatory = $true, HelpMessage = "SharePoint admin center URL, e.g. https://contoso-admin.sharepoint.com")] + [ValidatePattern('^https://')] + [string]$AdminUrl, + + [Parameter(HelpMessage = "Optional credential for unattended execution")] + [System.Management.Automation.PSCredential]$Credential, + + [Parameter(HelpMessage = "Switch to use device code flow instead of interactive login")] + [switch]$UseDeviceCode, + + [Parameter(HelpMessage = "Optional CSV file path to export site inventory")] + [string]$OutputPath +) + +try { + if (-not (Get-Module -ListAvailable -Name PnP.PowerShell)) { + throw "PnP.PowerShell module is not installed. Install it with 'Install-Module PnP.PowerShell'." + } + + Import-Module PnP.PowerShell -ErrorAction Stop +} +catch { + throw "Unable to load PnP.PowerShell module: $($_.Exception.Message)" +} + +try { + Write-Verbose "Connecting to tenant via $AdminUrl" + + if ($Credential) { + Connect-PnPOnline -Url $AdminUrl -Credentials $Credential -ErrorAction Stop + } + elseif ($UseDeviceCode) { + Connect-PnPOnline -Url $AdminUrl -DeviceLogin -ErrorAction Stop + } + else { + Connect-PnPOnline -Url $AdminUrl -Interactive -ErrorAction Stop + } + + Write-Host "Connected to $AdminUrl" -ForegroundColor Green + + $sites = Get-PnPTenantSite -Detailed -ErrorAction Stop | Sort-Object Url + + if (-not $sites) { + Write-Warning "No sites returned. Ensure the account has tenant admin permissions." + return + } + + $siteSummary = $sites | Select-Object Url, Template, Owner, StorageUsageCurrent, LastContentModifiedDate + + $siteSummary | Format-Table -AutoSize + + if ($OutputPath) { + $siteSummary | Export-Csv -Path $OutputPath -NoTypeInformation -Encoding UTF8 + Write-Host "Exported site inventory to $OutputPath" -ForegroundColor Cyan + } +} +catch { + Write-Error "Failed to retrieve sites: $($_.Exception.Message)" +} +finally { + Disconnect-PnPOnline -ErrorAction SilentlyContinue | Out-Null +}