Skip to content
Draft
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
64 changes: 64 additions & 0 deletions SharePointOnline/ListAllSitesPnP.ps1
Original file line number Diff line number Diff line change
@@ -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
}