クライアントシークレットを環境変数から取得する

まず環境変数にクライアントシークレットを登録する。(値はダミー)

$clinetSecret = "bXw7Q~Pn0fv8NHXBZdWzgkRm2gzFd-.fsZx~O"
[System.Environment]::SetEnvironmentVariable("ClientSecret", $clinetSecret, "User")

登録後 PowerShell を再起動しないと環境変数を読み取れないので注意。

呼出し側。

$config = Get-Content -Path $PSScriptRoot\appsettings.json | ConvertFrom-Json

$applicationId = $config.applicationId
$directoryId = $config.directoryId

$scope = "https://graph.microsoft.com/.default"

$clientSecret = $env:ClientSecret # 環境変数から取得

$response = Invoke-RestMethod -Uri "https://login.microsoftonline.com/$directoryId/oauth2/v2.0/token" -Method Post -Body @{client_id=$applicationId; scope=$scope; client_secret=$clientSecret; grant_type="client_credentials"}
$accessToken = $response.access_token

$headers = @{"Authorization" = "Bearer " + $accessToken}
$users = Invoke-WebRequest -Uri https://graph.microsoft.com/v1.0/users -Headers $headers | ConvertFrom-Json

$users.value | Select-Object UserPrincipalName