Export Calendar Events to CSV with Microsoft Graph PowerShell
Managing calendar events is crucial for individuals and organizations using Microsoft 365. With the Microsoft Graph PowerShell SDK, you can automate the process of listing all calendars for a specific user and exporting their events to a CSV file for analysis or reporting.
In this guide, you’ll learn how to:
- Connect to Microsoft Graph using a registered app.
- List all calendars for a user.
- Fetch events from a selected calendar.
- Export calendar events to a CSV file.
Prerequisites
Before you start, ensure that you have the following:
1. Microsoft Graph PowerShell SDK Installed
Install it using this command:
Install-Module -Name Microsoft.Graph -Scope CurrentUser
2. App Registration in Azure AD
You need to register an app in Azure Active Directory (Azure AD) with the appropriate permissions:
- Calendars.Read – To read calendar data.
- Calendars.ReadWrite – To read and write calendar data.
For detailed steps on how to register an app and obtain the necessary credentials, check out this guide.
3. Connecting to Microsoft Graph
Once you have registered your app and obtained the Client ID, Tenant ID, and Client Secret, use the code below to authenticate and connect to Microsoft Graph.
Connecting to Microsoft Graph
Use the following code to establish a connection to Microsoft Graph:
# Configuration
$ClientId = "Your-Client-ID" # Replace with your Client ID
$TenantId = "Your-Tenant-ID" # Replace with your Tenant ID
$ClientSecret = "Your-Client-Secret" # Replace with your Client Secret
# Convert the client secret to a secure string
$ClientSecretPass = ConvertTo-SecureString -String $ClientSecret -AsPlainText -Force
# Create a credential object using the client ID and secure string
$ClientSecretCredential = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $ClientId, $ClientSecretPass
# Connect to Microsoft Graph with Client Secret
Connect-MgGraph -TenantId $TenantId -ClientSecretCredential $ClientSecretCredential
PowerShell Script to List Calendars and Export Events
Once connected to Microsoft Graph, use the following script to:
- Prompt for a user email.
- List all available calendars for the user.
- Prompt for a specific calendar name.
- Fetch and display the events.
- Export the events to a CSV file on your desktop.
The Complete Script
# Prompt for User Email
$userEmail = Read-Host "Enter the User's Email Address"
# Get the User's ID from their email
try {
$user = Get-MgUser -UserId $userEmail
$userId = $user.Id
} catch {
Write-Output "Error: Unable to find user with email '$userEmail'. Please check and try again."
exit
}
# Get and list all calendars for the user
Write-Output "Fetching calendars for user '$userEmail'..."
$calendars = Get-MgUserCalendar -UserId $userId
if ($calendars) {
Write-Output "Available Calendars:"
$calendars | ForEach-Object {
Write-Output " - $($_.Name)"
}
} else {
Write-Output "No calendars found for user '$userEmail'."
exit
}
# Prompt for the Calendar Name
$calendarName = Read-Host "Enter the Calendar Name from the list above"
# Find the calendar matching the name
$calendar = $calendars | Where-Object { $_.Name -eq $calendarName }
if ($calendar) {
Write-Output "Calendar '$calendarName' found with ID: $($calendar.Id)"
# Get events from the specified calendar
$events = Get-MgUserCalendarEvent -UserId $userId -CalendarId $calendar.Id
if ($events) {
# Prepare the events data for CSV export
$eventsData = $events | Select-Object `
@{Name="Subject";Expression={$_.Subject}}, `
@{Name="Start Date";Expression={($_.Start.DateTime | Get-Date -Format "MM/dd/yyyy hh:mm tt")}}, `
@{Name="End Date";Expression={($_.End.DateTime | Get-Date -Format "MM/dd/yyyy hh:mm tt")}}, `
@{Name="Location";Expression={$_.Location.DisplayName}}, `
@{Name="Description";Expression={[System.Text.RegularExpressions.Regex]::Replace($_.Body.Content, '<.*?>', '')}}
# Output to console and save to CSV
$csvFilePath = "$env:USERPROFILE\Desktop\CalendarEvents.csv"
$eventsData | Format-Table -AutoSize
$eventsData | Export-Csv -Path $csvFilePath -NoTypeInformation -Encoding UTF8
Write-Output "Events have been saved to '$csvFilePath'."
} else {
Write-Output "No events found in calendar '$calendarName'."
}
} else {
Write-Output "Error: No calendar found with the name '$calendarName'. Please check the calendar name and try again."
}
How the Script Works
1. Prompt for User Email
The script prompts you to enter the user’s email address to fetch their calendars.
$userEmail = Read-Host "Enter the User's Email Address"
2. Fetch and List Calendars
It retrieves and displays all calendars associated with the user.
$calendars = Get-MgUserCalendar -UserId $userId
3. Select and Fetch Calendar Events
After selecting a calendar, the script fetches all events from it.
$events = Get-MgUserCalendarEvent -UserId $userId -CalendarId $calendar.Id
4. Remove HTML from Event Descriptions
The script removes any HTML tags from event descriptions for clean output.
[System.Text.RegularExpressions.Regex]::Replace($_.Body.Content, '<.*?>', '')
5. Export Events to CSV
Finally, the events are saved to a CSV file on your desktop.
$csvFilePath = "$env:USERPROFILE\Desktop\CalendarEvents.csv"
$eventsData | Export-Csv -Path $csvFilePath -NoTypeInformation -Encoding UTF8
Sample Output
Console Output
Fetching calendars for user 'user@example.com'...
Available Calendars:
- Work Calendar
- Personal Calendar
- Team Meetings
Enter the Calendar Name from the list above: Work Calendar
Calendar 'Work Calendar' found with ID: A1B2C3D4
Events in 'Work Calendar':
Subject Start Date End Date Location Description
------- ---------- -------- -------- -----------
Team Meeting 11/28/2024 10:00 AM 11/28/2024 11:00 AM Conference Room Discussion on progress
CSV Output
The script saves the events in a CSV file named CalendarEvents.csv
on the desktop.
Subject | Start Date | End Date | Location | Description |
---|---|---|---|---|
Team Meeting | 11/28/2024 10:00 AM | 11/28/2024 11:00 AM | Conference Room | Discussion on progress |
This PowerShell script provides a simple and efficient way to list calendars and export calendar events to a CSV file using Microsoft Graph. It’s a powerful tool for IT administrators and users who need to manage and analyze calendar data across their organization.
For more advanced scenarios or customization, refer to the Microsoft Graph PowerShell documentation.