PowerShell을 사용하여 보고서에서 사이트 URL resolve

이 문서에서는 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 관리 센터>애플리케이션>앱 등록 이동합니다.

  2. 앱 등록 페이지에서 새 등록을 선택합니다.

  3. 이 애플리케이션의 이름을 선택하고 기본 구성을 사용하여 앱을 등록합니다.

클라이언트 ID테넌트 ID는 앱의 Essentials 섹션에 표시됩니다.

클라이언트 및 필드 ID가 강조 표시된 필드를 보여 주는 스크린샷

앱에 Graph 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 스크립트를 보려면 업데이트-보고서 PowerShell을 참조하세요.

스크립트는 위에서 만든 비밀의 값을 입력하도록 요청합니다.

클라이언트 암호에 대한 PowerShell 명령을 보여 주는 스크린샷

스크립트를 실행한 후 사이트 URL이 추가된 새 버전의 보고서가 만들어집니다.

사용 보고서에 포함된 사이트 URL 목록을 보여 주는 스크린샷

환경 정리

환경을 클린 애플리케이션의 인증서 & 비밀 페이지로 돌아가서 이전에 만든 비밀을 삭제합니다.

SSD(반도체 드라이브)를 사용하여 IO 성능을 개선합니다. 사용 가능한 메모리/사용되지 않는 메모리가 충분한 컴퓨터에서 스크립트를 실행합니다. 캐시는 1,500만 개의 사이트에 대해 약 2GB가 소요됩니다.

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
}

마무리

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 사이트에 대한 정보를 검색할 수도 있습니다. 자세한 내용은 드라이브 리소스 종류를 참조하세요.

예를 들면 다음과 같습니다.

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