To list user calendars using PowerShell, the most straightforward approach is to use the Microsoft Graph API. Below, I'll walk you through how to create a PowerShell script to list user calendars. Keep in mind that you need the `Microsoft.Graph` module and the necessary permissions to access user calendars.
### Prerequisites
1. **App Registration**: Register an application in Azure AD and delegate the appropriate Graph API permissions (e.g., `Calendars.Read`, `Calendars.Read.Shared`).
2. **Install Microsoft Graph Module**: Install the `Microsoft.Graph` module in PowerShell.
### Steps
1. **Register Application and Set API Permissions**:
- Go to the Azure portal and register a new app.
- Assign `Calendars.Read` permissions.
- Generate a client secret and note the client ID, tenant ID, and client secret.
2. **Install Microsoft.Graph Module (if not already installed)**:
```powershell
Install-Module Microsoft.Graph -Scope CurrentUser
```
3. **PowerShell Script**:
```powershell
# Parameters
$tenantId = "Your_Tenant_ID"
$clientId = "Your_Client_ID"
$clientSecret = "Your_Client_Secret"
$userId = "
[email protected]" # The user whose calendars you want to list
# Connect to Microsoft Graph
$body = @{
grant_type = "client_credentials"
scope = "https://graph.microsoft.com/.default"
client_id = $clientId
client_secret = $clientSecret
}
$oauthTokenUri = "https://login.microsoftonline.com/$tenantId/oauth2/v2.0/token"
$tokenResponse = Invoke-RestMethod -Method Post -Uri $oauthTokenUri -ContentType "application/x-www-form-urlencoded" -Body $body
$accessToken = $tokenResponse.access_token
# Set Authentication Header
$headers = @{
Authorization = "Bearer $accessToken"
ContentType = "application/json"
}
# Endpoint to get user calendars
$uri = "https://graph.microsoft.com/v1.0/users/$userId/calendars"
# Make the Request
$response = Invoke-RestMethod -Method Get -Uri $uri -Headers $headers
# Output the calendars
$response.value | Select-Object id, name
```
### Explanation
1. **OAuth 2.0 Client Credentials Flow**: This script uses client credentials flow to obtain an access token, which is used for authenticating requests to the Microsoft Graph API.
2. **Connect to Microsoft Graph**: It sends a POST request to the OAuth 2.0 token endpoint to get an access token.
3. **List Calendars**: It sends a GET request to the `/users/{user-id}/calendars` endpoint to retrieve a list of calendars for the specified user.
4. **Output**: It selects and outputs the ID and Name of each calendar.
[[MG-UserMessage read user messages]]