🚀 Export Your Copilot Studio Agents Like a Pro!
🚀 Export Your Copilot Studio Agents Like a Pro!
The Ultimate Beginner's Guide to Automating Copilot Agent Exports from Power Platform
📦 Complete with PowerShell Script & Step-by-Step InstructionsHey there, Power Platform enthusiast! 👋
Are you tired of manually tracking your Copilot Studio agents? Wishing there was an easier way to get a list of all your agents with their owners, status, and creation dates? Well, you're in luck!
In this guide, I'll walk you through EVERYTHING you need to create an automated solution that exports all your Copilot Studio agents to a CSV file. And the best part? Once it's set up, you can run it with a single click! 🎉
So grab your favorite beverage ☕, and let's dive in!
📑 What's in This Guide
📋 Part 1: Prerequisites
Before we start, let's make sure you have everything you need. Don't worry if something seems unfamiliar – I'll explain each item!
System Requirements
| Requirement | Minimum Version | Notes |
|---|---|---|
| Windows | Windows 10 or 11 | 64-bit recommended |
| PowerShell | Version 5.1 or higher | PowerShell 7 recommended |
| Internet Connection | Stable broadband | Required for API calls |
| Web Browser | Edge, Chrome, or Firefox | For Azure Portal access |
Access Requirements
| Access Type | Why You Need It |
|---|---|
| Azure Portal Access | To create the App Registration that authenticates our script |
| Global Admin or Cloud App Admin | To grant admin consent for API permissions |
| Power Platform Admin | To create Application User and access environments |
| Copilot Studio License | You need at least one environment with Copilot Studio agents |
🔐 Part 2: Azure App Registration
Think of an App Registration as creating an "ID card" for our script. This ID card tells Microsoft who is making the API requests and what they're allowed to access.
Step 2.1: Create the App Registration
- Name: Copilot-Studio-Export (or any name you prefer)
- Supported account types: Accounts in this organizational directory only
- Redirect URI: Leave blank (we don't need it)
Step 2.2: Copy Your IDs (IMPORTANT!)
After registration, you'll see the Overview page. You need to copy TWO important values:
| What to Copy | What It's Called in the Script |
|---|---|
| Application (client) ID | This is your $ClientId - looks like: xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx |
| Directory (tenant) ID | This is your $TenantId - looks like: xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx |
Step 2.3: Create a Client Secret
The Client Secret is like a password for your app. Here's how to create one:
$ClientSecret🔑 Part 3: Configure API Permissions
Now we need to tell Azure what our app is allowed to access. Think of this as giving your ID card the right "access levels."
Required Permissions
| Permission Name | Type | What It Does |
|---|---|---|
| Reports.Read.All | Application | Allows reading usage reports and Copilot data |
| User.Read.All | Application | Allows looking up user names (for agent owners) |
| Directory.Read.All | Application | Allows reading directory information (optional) |
Step 3.1: Add the Permissions
Step 3.2: Grant Admin Consent
This is a crucial step! Without admin consent, the permissions won't work.
⚡ Part 4: Power Platform Application User
This is where we give our app access to Dataverse (the database where Copilot Studio agents are stored). Without this step, the script can't read your agents!
Step 4.1: Open Power Platform Admin Center
Step 4.2: Navigate to Your Environment
Step 4.3: Create Application User
📦 Part 5: Install PowerShell Modules
Now let's set up your computer to run the script. We need to install two PowerShell modules.
Required Modules
| Module Name | Required? | Purpose |
|---|---|---|
Microsoft.PowerApps.Administration.PowerShell | ✅ Required | Connect to Power Platform and discover environments |
Microsoft.Xrm.Tooling.CrmConnector.PowerShell | ✅ Required | Connect to Dataverse and query agent data |
Step 5.1: Open PowerShell as Administrator
Step 5.2: Install the Modules
Copy and paste these commands into PowerShell and press Enter after each one:
Module 1: Power Apps Administration
Install-Module -Name Microsoft.PowerApps.Administration.PowerShell -Force -Scope CurrentUserModule 2: CRM Connector (Dataverse)
Install-Module Microsoft.Xrm.Tooling.CrmConnector.PowerShell -Force -Scope CurrentUserIf prompted to install from an untrusted repository, type Y and press Enter.
Get-Module -ListAvailable | Where-Object {$_.Name -like "*PowerApps*" -or $_.Name -like "*Xrm*"}💻 Part 6: The PowerShell Script
Here's the moment you've been waiting for! 🎉
Step 6.1: Create the Script File
- Open Notepad (search for it in the Start menu)
- Copy the ENTIRE script below
- Paste it into Notepad
- Save the file as Export-CopilotStudioAgents.ps1 in C:\mcp\
Step 6.2: Where to Enter Your Credentials
IMPORTANT: You MUST update three values at the top of the script with YOUR values from Part 2!
| Variable Name | Replace This | With This (Your Value) |
|---|---|---|
$TenantId | YOUR_TENANT_ID_HERE | Your Directory (tenant) ID from Azure |
$ClientId | YOUR_CLIENT_ID_HERE | Your Application (client) ID from Azure |
$ClientSecret | YOUR_CLIENT_SECRET_HERE | Your secret Value from Azure |
Look for lines 16-18 in the script – they look like this:
# ============================================================================
# CONFIGURATION - ENTER YOUR VALUES HERE
# ============================================================================
$TenantId = "YOUR_TENANT_ID_HERE" # <-- REPLACE THIS
$ClientId = "YOUR_CLIENT_ID_HERE" # <-- REPLACE THIS
$ClientSecret = "YOUR_CLIENT_SECRET_HERE" # <-- REPLACE THIS
# ============================================================================📄 Complete PowerShell Script
<#
.SYNOPSIS
All-in-One Copilot Studio Agents Export Tool
.DESCRIPTION
Automatically discovers Dataverse environments and exports all
Copilot Studio agents to CSV. Just enter your credentials and run!
.NOTES
Version: 6.0
#>
# ============================================================================
# CONFIGURATION - ENTER YOUR VALUES HERE
# ============================================================================
$TenantId = "YOUR_TENANT_ID_HERE" # Directory (tenant) ID from Azure
$ClientId = "YOUR_CLIENT_ID_HERE" # Application (client) ID from Azure
$ClientSecret = "YOUR_CLIENT_SECRET_HERE" # Secret Value from Azure
# ============================================================================
# Output Settings
$OutputFolder = "C:\mcp"
$Timestamp = Get-Date -Format "yyyyMMdd_HHmmss"
$OutputFile = "$OutputFolder\CopilotStudioAgents_$Timestamp.csv"
Write-Host ""
Write-Host "======================================================================" -ForegroundColor Cyan
Write-Host " Copilot Studio Agents Export - All-in-One v6.0" -ForegroundColor Cyan
Write-Host "======================================================================" -ForegroundColor Cyan
Write-Host ""
# Validate credentials
if ($TenantId -eq "YOUR_TENANT_ID_HERE" -or $ClientId -eq "YOUR_CLIENT_ID_HERE" -or $ClientSecret -eq "YOUR_CLIENT_SECRET_HERE") {
Write-Host "============================================================" -ForegroundColor Red
Write-Host " ERROR: Please update your credentials in the script!" -ForegroundColor Red
Write-Host "============================================================" -ForegroundColor Red
Write-Host ""
Write-Host "Open this script in Notepad and edit lines 16-18:" -ForegroundColor Yellow
Write-Host ""
Write-Host ' $TenantId = "paste-your-tenant-id-here"' -ForegroundColor Gray
Write-Host ' $ClientId = "paste-your-client-id-here"' -ForegroundColor Gray
Write-Host ' $ClientSecret = "paste-your-secret-value-here"' -ForegroundColor Gray
Write-Host ""
exit 1
}
# Create output folder
if (-not (Test-Path $OutputFolder)) {
New-Item -ItemType Directory -Path $OutputFolder -Force | Out-Null
Write-Host "Created folder: $OutputFolder" -ForegroundColor Gray
}
# ============================================================================
# STEP 1: Install Required Modules
# ============================================================================
Write-Host "STEP 1: Checking PowerShell modules..." -ForegroundColor Cyan
# Module 1: Power Apps Administration
$module1 = "Microsoft.PowerApps.Administration.PowerShell"
if (-not (Get-Module -ListAvailable -Name $module1)) {
Write-Host " Installing $module1..." -ForegroundColor Yellow
Install-Module -Name $module1 -Force -AllowClobber -Scope CurrentUser
}
Write-Host " $module1 - OK" -ForegroundColor Green
# Module 2: CRM Connector
$module2 = "Microsoft.Xrm.Tooling.CrmConnector.PowerShell"
if (-not (Get-Module -ListAvailable -Name $module2)) {
Write-Host " Installing $module2..." -ForegroundColor Yellow
Install-Module -Name $module2 -Force -Scope CurrentUser
}
Write-Host " $module2 - OK" -ForegroundColor Green
# Import modules
Import-Module $module1 -Force -ErrorAction SilentlyContinue
Import-Module $module2 -Force -ErrorAction SilentlyContinue
# ============================================================================
# STEP 2: Connect to Power Platform (Interactive Login)
# ============================================================================
Write-Host ""
Write-Host "STEP 2: Connecting to Power Platform..." -ForegroundColor Cyan
Write-Host " (A browser window will open for sign-in)" -ForegroundColor Gray
try {
Add-PowerAppsAccount
Write-Host " Connected successfully!" -ForegroundColor Green
} catch {
Write-Host " Connection failed: $($_.Exception.Message)" -ForegroundColor Red
exit 1
}
# ============================================================================
# STEP 3: Get All Environments and Dataverse URLs
# ============================================================================
Write-Host ""
Write-Host "STEP 3: Discovering environments..." -ForegroundColor Cyan
$environments = @()
try {
$environments = Get-AdminPowerAppEnvironment
Write-Host " Found $($environments.Count) environment(s)" -ForegroundColor Green
} catch {
Write-Host " Error: $($_.Exception.Message)" -ForegroundColor Red
exit 1
}
# Build list of environments with Dataverse URLs
$envList = @()
foreach ($env in $environments) {
$instanceUrl = $null
try {
$instanceUrl = $env.Internal.properties.linkedEnvironmentMetadata.instanceUrl
} catch {}
if ($instanceUrl) {
$envList += [PSCustomObject]@{
Name = $env.DisplayName
Id = $env.EnvironmentName
Url = $instanceUrl
}
Write-Host " - $($env.DisplayName): $instanceUrl" -ForegroundColor Gray
} else {
Write-Host " - $($env.DisplayName): No Dataverse" -ForegroundColor DarkGray
}
}
if ($envList.Count -eq 0) {
Write-Host " No Dataverse environments found!" -ForegroundColor Red
exit 1
}
# ============================================================================
# STEP 4: Query Each Environment for Bots
# ============================================================================
Write-Host ""
Write-Host "STEP 4: Querying Copilot Studio agents..." -ForegroundColor Cyan
$allAgents = @()
$tokenEndpoint = "https://login.microsoftonline.com/$TenantId/oauth2/v2.0/token"
foreach ($envInfo in $envList) {
Write-Host ""
Write-Host " Environment: $($envInfo.Name)" -ForegroundColor White
$dataverseUrl = $envInfo.Url.TrimEnd('/')
# Get token for this environment
$body = @{
client_id = $ClientId
client_secret = $ClientSecret
scope = "$dataverseUrl/.default"
grant_type = "client_credentials"
}
try {
$tokenResponse = Invoke-RestMethod -Uri $tokenEndpoint -Method Post -Body $body -ContentType "application/x-www-form-urlencoded"
$accessToken = $tokenResponse.access_token
Write-Host " Authenticated successfully" -ForegroundColor Green
} catch {
Write-Host " Auth failed - App may not be registered as Application User" -ForegroundColor Yellow
Write-Host " See Guide: Power Platform Admin > Environments > Settings > Application users" -ForegroundColor Gray
continue
}
# Query Dataverse for bots
$headers = @{
"Authorization" = "Bearer $accessToken"
"OData-MaxVersion" = "4.0"
"OData-Version" = "4.0"
"Accept" = "application/json"
"Prefer" = "odata.include-annotations=*"
}
$botsUri = "$dataverseUrl/api/data/v9.2/bots?`$select=name,botid,createdon,modifiedon,publishedon,statecode,statuscode,_ownerid_value,language,schemaname&`$orderby=createdon desc"
try {
$response = Invoke-RestMethod -Uri $botsUri -Headers $headers -Method Get
if ($response.value -and $response.value.Count -gt 0) {
Write-Host " Found $($response.value.Count) agent(s)" -ForegroundColor Green
foreach ($bot in $response.value) {
$ownerName = $bot.'_ownerid_value@OData.Community.Display.V1.FormattedValue'
if (-not $ownerName) { $ownerName = "Unknown" }
$status = switch ($bot.statecode) {
0 { "Active" }
1 { "Inactive" }
default { "Unknown" }
}
$allAgents += [PSCustomObject]@{
AgentName = $bot.name
Owner = $ownerName
Status = $status
Language = $bot.language
CreatedOn = $bot.createdon
ModifiedOn = $bot.modifiedon
PublishedOn = $bot.publishedon
AgentId = $bot.botid
SchemaName = $bot.schemaname
Environment = $envInfo.Name
EnvironmentUrl = $dataverseUrl
}
}
} else {
Write-Host " No agents in this environment" -ForegroundColor Gray
}
} catch {
Write-Host " Query error: $($_.Exception.Message)" -ForegroundColor Yellow
}
}
# ============================================================================
# STEP 5: Export to CSV
# ============================================================================
Write-Host ""
Write-Host "STEP 5: Exporting results..." -ForegroundColor Cyan
if ($allAgents.Count -gt 0) {
# Sort by CreatedOn descending and add ranking
$sortedAgents = $allAgents | Sort-Object -Property CreatedOn -Descending
$rank = 1
$finalAgents = @()
foreach ($agent in $sortedAgents) {
$agent | Add-Member -NotePropertyName "Rank" -NotePropertyValue $rank -Force
$finalAgents += $agent
$rank++
}
# Export
$exportData = $finalAgents | Select-Object Rank, AgentName, Owner, Status, Environment, Language, CreatedOn, ModifiedOn, PublishedOn, AgentId, SchemaName, EnvironmentUrl
$exportData | Export-Csv -Path $OutputFile -NoTypeInformation -Encoding UTF8
Write-Host ""
Write-Host "======================================================================" -ForegroundColor Green
Write-Host " EXPORT COMPLETE!" -ForegroundColor Green
Write-Host "======================================================================" -ForegroundColor Green
Write-Host ""
Write-Host " Total Agents: $($finalAgents.Count)" -ForegroundColor White
Write-Host " Output File: $OutputFile" -ForegroundColor White
Write-Host ""
# Display summary
Write-Host "Copilot Studio Agents:" -ForegroundColor Cyan
Write-Host "----------------------------------------------------------------------" -ForegroundColor Gray
foreach ($agent in $finalAgents) {
$name = $agent.AgentName
if ($name.Length -gt 30) { $name = $name.Substring(0,27) + "..." }
$owner = $agent.Owner
if ($owner -and $owner.Length -gt 12) { $owner = $owner.Substring(0,9) + "..." }
Write-Host (" {0,2}. {1,-30} | Owner: {2,-12} | Status: {3,-8} | Env: {4}" -f $agent.Rank, $name, $owner, $agent.Status, $agent.Environment) -ForegroundColor White
}
Write-Host "----------------------------------------------------------------------" -ForegroundColor Gray
# Open folder
Write-Host ""
Write-Host "Opening export folder..." -ForegroundColor Gray
Start-Process explorer.exe -ArgumentList $OutputFolder
} else {
Write-Host ""
Write-Host "======================================================================" -ForegroundColor Yellow
Write-Host " No Copilot Studio agents found" -ForegroundColor Yellow
Write-Host "======================================================================" -ForegroundColor Yellow
Write-Host ""
Write-Host "Possible reasons:" -ForegroundColor White
Write-Host " 1. App not registered as Application User in Power Platform" -ForegroundColor Gray
Write-Host " 2. No agents created in your environments" -ForegroundColor Gray
Write-Host " 3. Check the Complete Guide document for setup instructions" -ForegroundColor Gray
}
Write-Host ""
Write-Host "Script completed at $(Get-Date -Format 'yyyy-MM-dd HH:mm:ss')" -ForegroundColor Cyan
Write-Host ""▶️ Part 7: Running the Script
You're almost there! Let's run the script and export your agents.
Final Checklist
- Saved the script as C:\mcp\Export-CopilotStudioAgents.ps1
- Replaced
YOUR_TENANT_ID_HEREwith your Tenant ID - Replaced
YOUR_CLIENT_ID_HEREwith your Client ID - Replaced
YOUR_CLIENT_SECRET_HEREwith your Client Secret - Created Application User in Power Platform (Part 4)
- Installed both PowerShell modules (Part 5)
Execute the Script
cd C:\mcp.\Export-CopilotStudioAgents.ps1🎉 What You'll Get
Your CSV file will contain these columns:
| Column | Description |
|---|---|
| Rank | Position in list (1 = most recently created) |
| AgentName | The name of your Copilot Studio agent |
| Owner | Who created/owns the agent |
| Status | Active or Inactive |
| Environment | Which Power Platform environment it's in |
| Language | Language setting of the agent |
| CreatedOn | When the agent was created |
| ModifiedOn | When it was last modified |
| PublishedOn | When it was last published |
| AgentId | Unique identifier (GUID) |
| SchemaName | Internal schema name |
| EnvironmentUrl | Dataverse URL of the environment |
🔧 Part 8: Troubleshooting
Running into issues? Here are solutions to the most common problems:
❌ Error: "Update your credentials in the script!"
- Cause: You haven't replaced the placeholder values
- Fix: Open the script in Notepad and update lines 16-18 with your actual values from Azure
❌ Error: "Auth failed - check Application User setup"
- Cause: Your app isn't registered as an Application User in Power Platform
- Fix: Go back to Part 4 and complete the Application User setup
❌ Error: "No agents found!"
- Cause 1: No Copilot Studio agents exist in your environments
- Cause 2: Application User doesn't have System Administrator role
- Fix: Check Power Platform Admin Center → Copilot Studio to verify agents exist
❌ Error: "Connection failed!"
- Cause: Browser sign-in was cancelled or failed
- Fix: Run the script again and complete the browser sign-in
❌ Error: "Cannot run scripts" / Execution Policy
- Cause: PowerShell script execution is disabled
- Fix: Run this command first:
Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser❌ Error: "Module not found"
- Cause: PowerShell modules weren't installed properly
- Fix: Run these commands as Administrator:
Install-Module -Name Microsoft.PowerApps.Administration.PowerShell -Force -Scope CurrentUser
Install-Module Microsoft.Xrm.Tooling.CrmConnector.PowerShell -Force -Scope CurrentUser🎉 Congratulations!
You've successfully set up automated Copilot Studio agent exports! 🎊
Now you can run this script anytime to get an up-to-date list of all your agents. Some ideas for next steps:
- 📅 Schedule the script to run weekly using Windows Task Scheduler
- 📊 Import the CSV into Excel or Power BI for reporting
- 👥 Share the script with your team!
Happy automating! 🤖💙
📚 Quick Reference Links
- Azure Portal - Manage App Registrations & Permissions
- Power Platform Admin Center - Manage Environments & Application Users
- Copilot Studio Documentation - Official Microsoft Docs
📋 Quick Reference Summary
| Item | Details |
|---|---|
| Azure Permissions | Reports.Read.All, User.Read.All, Directory.Read.All |
| PowerShell Modules | Microsoft.PowerApps.Administration.PowerShell Microsoft.Xrm.Tooling.CrmConnector.PowerShell |
| Power Platform Role | System Administrator (for Application User) |
| Script Location | C:\mcp\Export-CopilotStudioAgents.ps1 |
| Output Location | C:\mcp\CopilotStudioAgents_[timestamp].csv |
Comments
Post a Comment