Forum Discussion

pnm537's avatar
pnm537
Copper Contributor
Nov 22, 2024

Help With Site Inventory (SharePoint Online/PowerShell)

Hi, all,

I've been trying to do something I thought would be easy but isn't: Get a list of all of my tenant's SharePoint online sites and subsites.

I know this cannot be done in the SharePoint Admin Center (at least not subsites), so I turned to my nemesis, PowerShell. This code below is supposed to do just what I want but doesn't (error below code). I'm running it in the latest SharePoint Online Management Shell, and I just keep getting errors. Any help would be greatly appreciated.

Here is the code:

# Get all sites (including subsites) using SharePoint Online Management Shell
$sites = Get-SPOSite -Limit All

# Initialize an array to store site information
$siteDetails = @()

# Loop through each site to gather details
foreach ($site in $sites) {
    try {
        # Retrieve site details using Microsoft Graph API by site URL
        $siteGraphInfo = Get-MgSite -SiteId $site.Url

        # If the site details are retrieved, extract the necessary information
        $lastUsed = $siteGraphInfo.LastModifiedDateTime

        # Store details in an array
        $siteDetails += [PSCustomObject]@{
            'SiteName'       = $site.Title
            'SiteURL'        = $site.Url
            'LastUsed'       = $lastUsed
        }
    }
    catch {
        Write-Warning "Failed to retrieve site information for $($site.Url)"
    }
}

# Export the data to an Excel file
$siteDetails | Export-Excel -Path "C:\sharepoint_sites.xlsx" -AutoSize -AutoFilter

 

And here is the error:

Get-MgSite : Invalid hostname for this tenancy
Status: 400 (BadRequest)
ErrorCode: invalidRequest
Date: 2024-11-22T00:18:38
Headers:
Transfer-Encoding : chunked
Vary : Accept-Encoding
Strict-Transport-Security : max-age=31536000
request-id : *****-*****-*****-*****-*****
client-request-id : *****-*****-*****-*****-*****
x-ms-ags-diagnostic : {"ServerInfo":{"DataCenter":"Canada
East","Slice":"E","Ring":"3","ScaleUnit":"002","RoleInstance":"QB1PEPF000057A5"}}
Cache-Control : no-store, no-cache
Date : Fri, 22 Nov 2024 00:18:37 GMT
At line:4 char:9
+ $siteGraphInfo = Get-MgSite -SiteId $site.Url

+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

+ CategoryInfo : InvalidOperation: ({ SiteId = http... , Headers = }:<>f__AnonymousType191`4) [Get-MgSit
e_Get], Exception
+ FullyQualifiedErrorId : invalidRequest,Microsoft.Graph.PowerShell.Cmdlets.GetMgSite_Get

 

Thanks in advance.

Resources