top of page

PowerShell Script um Termine über MS-Graph auszulesen / PowerShell script to read appointments via MS-Graph

(alle Versionen/all versions)

Samstag, 23. Mai 2026

English


Background

Microsoft allows via Azure "MS-Graph" to query calendar information via REST.

The following quick example demonstrates this , using a simple approach via Tenant ID , Client ID and a Secret Code.


Example script

Enter the relevant data at the marked points in the code.

$tenantId     = "..."
$clientId     = "..."
$clientSecret = "..."
$postfach     = "your@mail.com"

# Token:
$tokenUrl  = "https://login.microsoftonline.com/$tenantId/oauth2/v2.0/token"

$tokenBody = "grant_type=client_credentials&client_id=$clientId&client_secret=$([Uri]::EscapeDataString($clientSecret))&scope=https://graph.microsoft.com/.default"

$token = Invoke-RestMethod `
    -Uri         $tokenUrl `
    -Method      Post `
    -Body        $tokenBody `
    -ContentType "application/x-www-form-urlencoded"

# Attention! The token will have an expiry date!
$bearer = $token.access_token
Write-Host "Token erhalten: OK ($($bearer.Substring(0,20))...)"

# Date as pure UTC , no offset-suffix
$start = (Get-Date).ToUniversalTime().AddDays(-60).ToString("yyyy-MM-ddTHH:mm:ss")

$end   = (Get-Date).ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ss")

# Attention! The API requires paging and will only return a max of currently ~999 records per page!
$url = "https://graph.microsoft.com/v1.0/users/$postfach/calendarView" +
"?startDateTime=$start&endDateTime=$end&`$top=999&`$select=subject,start,end,sensitivity"

Write-Host "Abfrage-URL: $url"

# Show possible exceptions:

try
{
    $result = Invoke-RestMethod `
        -Uri     $url `
        -Method  Get `
        -Headers @{ Authorization = "Bearer $bearer"; Accept = "application/json" }

    if ( $result.value.Count -eq 0 )
    {
        Write-Host "Abfrage OK, aber keine Termine im Zeitraum gefunden."
    }
    else
    {
       $result.value | Select-Object subject, sensitivity, @{n="Start";e={$_.start.dateTime}} | Format-Table
    }
}
catch
{
    $reader  = New-Object System.IO.StreamReader($_.Exception.Response.GetResponseStream())

    $detail  = $reader.ReadToEnd()

    Write-Host "FEHLER-DETAIL VON GRAPH:" -ForegroundColor Red
    Write-Host $detail
}

bottom of page