使用 PowerShell 解析報表中的網站 URL

本文涵蓋如何使用PowerShell在報表中顯示網站URL。

運作方式

圖形 API 提供可讓您列出組織內所有網站的 API。 若要使用此 API,您必須擁有具有 Sites.Read.All 許可權的應用程式。

腳本會叫用此 API 端點,以取得站臺標識碼與網站 URL 之間的對應,然後將網站 URL 新增至導出的 CSV 報表。

為何不使用委派的許可權?

  • /sites/getAllSites API 只接受應用程式許可權。

  • /sites?search=* API 接受委派的許可權,但即使使用系統管理員帳戶,也不會傳回所有網站。

步驟

若要使用PowerShell顯示網站URL,請遵循下列步驟。

建立 Entra ID 應用程式

  1. 移至 Microsoft Entra 系統管理中心>Applications>應用程式註冊

  2. 在 [應用程式註冊] 頁面上,選取 [新增註冊]

  3. 挑選此應用程式的名稱,並使用預設組態來註冊應用程式。

請記住, 用戶端標識碼租使用者標識碼 會顯示在應用程式的 Essentials 區 段中。

顯示已醒目提示用戶端和字段標識碼之欄位的螢幕快照。

將 圖形 API許可權新增至應用程式

在新應用程式的要求 API 許可權 頁面中,新增 Sites.Read.All 許可權。

顯示已選取 Sites.Read.All 許可權的螢幕快照。

然後,授與管理員同意。

顯示已選取 [授與管理員同意] 設定的螢幕快照。

建立用戶端密碼

在新應用程式的 [ 憑證 & 秘密 ] 區段中,建立新的客戶端密碼。 然後,將 秘密的值 儲存在安全的地方。

顯示建立新客戶端密碼步驟的螢幕快照。

在 Microsoft 365 系統管理中心 中下載報表

在兩個報表頁面上下載網站詳細數據報表,並將 CSV 報表檔案放在本機資料夾下。

下載報表之前,請務必關閉使用者詳細數據的隱私權設定。 如需詳細資訊,請參閱 Microsoft 365 系統管理中心 活動報告

針對 SharePoint 網站使用量,請移至 Microsoft 365 系統管理中心 中的 SharePoint 網站使用量頁面。

針對 OneDrive 網站使用量,請移至 Microsoft 365 系統管理中心 中的 OneDrive 網站使用量頁面。

使用網站 URL 更新報表

若要使用網站 URL 更新報表,請執行 PowerShell 腳本。

.\Update-Report.ps1 -**tenantId** {tenant id above} -**clientId** {client id above} -**reportPaths** @("file path for report \#1", "file path for report \#2")

若要檢視完整 Update-Report PowerShell 腳本,請參閱 Update-Report PowerShell

腳本會要求您輸入上面建立 的秘密值

顯示客戶端密碼之 PowerShell 命令的螢幕快照。

執行腳本之後,會建立新版本的報表,並新增網站 URL。

顯示使用量報表中所包含網站 URL 清單的螢幕快照。

清除環境

若要清除環境,請返回應用程式的 [ 憑證 & 秘密 ] 頁面,並刪除稍早建立的秘密。

提示

使用 SSD (固態硬碟) 來改善 IO 效能。 在具有足夠可用/未使用記憶體的計算機上執行腳本。 1500 萬個月臺的快取大約需要 2GB。

Update-Report PowerShell 腳本

以下是 Update-Report 的 PowerShell 腳本。

 param(
 [Parameter(Mandatory=$true)]
 [string]$tenantId,
 [Parameter(Mandatory=$true)]
 [string]$clientId,
 [Parameter(Mandatory=$false)]
 [string[]]$reportPaths
)

function Get-AccessToken {
 param(
     [Parameter(Mandatory=$true)]
     [string]$tenantId,
     [Parameter(Mandatory=$true)]
     [string]$clientId,
     [Parameter(Mandatory=$true)]
     [System.Security.SecureString]$clientSecret,
     [Parameter(Mandatory=$false)]
     [string]$scope = "https://graph.microsoft.com/.default"
 )

 $tokenEndpoint = "https://login.microsoftonline.com/$tenantId/oauth2/v2.0/token"
 $tokenRequest = @{
     client_id     = $clientId
     scope         = $scope
     client_secret = ConvertFrom-SecureString $clientSecret -AsPlainText
     grant_type    = "client_credentials"
 }

 $tokenResponse = Invoke-RestMethod -Uri $tokenEndpoint -Method Post -Body $tokenRequest
 return $tokenResponse.access_token
}

準備快取和客戶端密碼

if ($reportPaths.Count -eq 0) {
  Write-Host "Please provide at least one report path" -ForegroundColor Red
  exit
}
$cache = New-Object 'System.Collections.Generic.Dictionary[[String],[String]]'
$clientSecret = Read-Host "Please enter client secret" -AsSecureString

從 圖形 API 擷取網站資訊

Write-Host
Write-Host "Getting information for all the sites..." -ForegroundColor Cyan

$uri = "https://graph.microsoft.com/v1.0/sites/getAllSites?`$select=sharepointIds&`$top=10000"
while ($uri -ne $null) {

  Write-Host $uri

  $isSuccess = $false
  while (-not $isSuccess) {
      try {
          $accessToken = Get-AccessToken -tenantId $tenantId -clientId $clientId -clientSecret $clientSecret
          $restParams = @{Headers=@{Authorization="Bearer $accessToken"}}
      }
      catch {
          Write-Host "Retrying...  $($_.Exception.Message)" -ForegroundColor Yellow
          continue
      }
      try {
          $sites = Invoke-RestMethod $uri @restParams
          $isSuccess = $true
      }
      catch {
          if ($_.Exception.Response -and $_.Exception.Response.Headers['Retry-After']) {
              $retryAfter = [int]$_.Exception.Response.Headers['Retry-After']
              Write-Output "Waiting for $retryAfter seconds before retrying..." -ForegroundColor Yellow
              Start-Sleep -Seconds $retryAfter
          }
          Write-Host "Retrying...  $($_.Exception.Message)" -ForegroundColor Yellow
          continue
      }
  }

  $sites.value | ForEach-Object {
      $cache[$_.sharepointIds.siteId] = $_.sharepointIds.siteUrl
  }

  $uri = $sites."@odata.nextLink"

  Write-Host "Total sites received: $($cache.Count)"
}

使用快取的網站資訊更新報表

foreach ($reportPath in $reportPaths) {
  Write-Host
  Write-Host "Updating report $($reportPath) ..." -ForegroundColor Cyan

  $outputPath = "$($reportPath)_$([Math]::Floor((Get-Date -UFormat %s))).csv"
  $writer = [System.IO.StreamWriter]::new($outputPath)
  $reader = [System.IO.StreamReader]::new($reportPath)
  $rowCount = 0

  while ($null -ne ($line = $reader.ReadLine())) {
      $rowCount++

      $columns = $line.Split(",")
      $siteId = $columns[1]

      $_guid = New-Object System.Guid
      if ([System.Guid]::TryParse($siteId, [ref]$_guid)) {
          $siteUrl = $cache[$siteId]
          $columns[2] = $siteUrl
          $line = $columns -join ","
      }
      
      $writer.WriteLine($line)

      if ($rowCount%1000 -eq 0) {
          Write-Host "Processed $($rowCount) rows"
      }
  }
  $writer.Close()
  $reader.Close()

  Write-Host "Processed $($rowCount) rows"
  Write-Host "Report updated: $($outputPath)" -ForegroundColor Cyan
}

完成

Write-Host
Read-Host "Press any key to exit..."

小型案例的其他選項

針對較小的規模案例,具有適當存取權的系統管理員可以使用 SharePoint REST API 或 Microsoft 圖形 API 來擷取受影響報告中所參考網站標識符的相關信息。 SharePoint REST API 可用來擷取特定網站標識碼的相關信息。

例如,下列 SharePoint REST API 要求會擷取網站標識碼為 15d43f38-ce4e-4f6b-bac6-766ece1fbcb4 的 Contoso 網站相關信息:

https://contoso.sharepoint.com/_api/v2.1/sites/contoso.sharepoint.com,15d43f38-ce4e-4f6b-bac6-766ece1fbcb4

Microsoft 圖形 API 可用來列出 SharePoint 網站或擷取特定網站標識碼的相關信息。 如需詳細資訊,請參閱 網站資源類型

例如:

  • https://graph.microsoft.com/v1.0/sites?search=*&$select=sharepointIds
  • https://graph.microsoft.com/v1.0/sites/{siteId}

Microsoft 圖形 API 也可以用來擷取指定使用者 商務用 OneDrive 網站的相關信息。 如需詳細資訊,請參閱 磁碟驅動器資源類型

例如:

  • https://graph.microsoft.com/v1.0/users/{userId}/drives?$select=sharepointIds