PowerShell を使用してレポート内のサイト URL を解決する

この記事では、PowerShell を使用してレポートにサイト URL を表示する方法について説明します。

メカニズム

Graph APIは、organization内のすべてのサイトを一覧表示できる API を提供します。 この API を使用するには、Sites.Read.All アクセス許可を持つアプリケーションが必要です。

このスクリプトは、この API エンドポイントを呼び出してサイト ID とサイト URL の間のマッピングを取得し、エクスポートされた CSV レポートにサイト URL を追加します。

委任されたアクセス許可を使用しないのはなぜですか?

  • /sites/getAllSites API は、アプリケーションのアクセス許可のみを受け入れます。

  • /sites?search=* API は委任されたアクセス許可を受け入れますが、管理者アカウントを使用してもすべてのサイトが返されるわけではありません。

手順

PowerShell を使用してサイト URL を表示するには、次の手順に従います。

Entra ID アプリケーションを作成する

  1. [Microsoft Entra 管理センター>Applicationsアプリの登録] に移動します>。

  2. [アプリの登録] ページで、[新しい登録] を選択します。

  3. このアプリケーションの名前を選択し、既定の構成を使用してアプリを登録します。

クライアント IDテナント ID は、アプリの [要点] セクションに表示されます。

クライアントとフィールド ID のフィールドが強調表示されているスクリーンショット。

アプリGraph APIアクセス許可を追加する

新しいアプリケーションの [API アクセス許可の要求] ページで、Sites.Read.All アクセス許可を追加します。

[Sites.Read.All] アクセス許可が選択されていることを示すスクリーンショット。

次に、管理者の同意を付与します。

[管理者の同意の付与] 設定が選択されていることを示すスクリーンショット。

クライアント シークレットを作成する

新しいアプリケーションの [証明書 & シークレット ] セクションで、新しいクライアント シークレットを作成します。 次に、 シークレットの値 を安全で安全な場所に格納します。

新しいクライアント シークレットを作成する手順を示すスクリーンショット。

Microsoft 365 管理センターでレポートをダウンロードする

2 つのレポート ページにサイトの詳細レポートをダウンロードし、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")

PowerShell スクリプトの完全な Update-Report を表示するには、「 Update-Report PowerShell」を参照してください。

スクリプトでは、上記で作成した シークレットの値を 入力するように求められます。

クライアント シークレットの PowerShell コマンドを示すスクリーンショット。

スクリプトを実行すると、サイト URL が追加された新しいバージョンのレポートが作成されます。

使用状況レポートに含まれるサイト URL の一覧を示すスクリーンショット。

環境をクリーンアップする

環境をクリーンするには、アプリケーションの [証明書 & シークレット] ページに戻り、先ほど作成したシークレットを削除します。

ヒント

SSD (ソリッド ステート ドライブ) を使用して IO パフォーマンスを向上させます。 十分な空き/未使用のメモリを持つマシンでスクリプトを実行します。 キャッシュは、1,500 万のサイトで約 2 GB かかります。

PowerShell スクリプトの Update-Report

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

Graph 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
}

Finalize

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

小規模シナリオの追加オプション

小規模なシナリオでは、適切なアクセス権を持つ管理者は、SharePoint REST API または Microsoft Graph APIを使用して、影響を受けるレポートで参照されているサイト ID に関する情報を取得できます。 SharePoint REST API を使用して、特定のサイト ID に関する情報を取得できます。

たとえば、次の SharePoint REST API 要求は、サイト ID 15d43f38-ce4e-4f6b-bac6-766ece1fbcb4 を持つ Contoso サイトに関する情報を取得します。

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

Microsoft Graph APIを使用すると、SharePoint サイトを一覧表示したり、特定のサイト ID に関する情報を取得したりできます。 詳細については、「 サイト リソースの種類」を参照してください。

例:

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

Microsoft Graph APIを使用して、特定のユーザーのOneDrive for Business サイトに関する情報を取得することもできます。 詳細については、「 ドライブ リソースの種類」を参照してください。

次に例を示します。

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