🚀 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 Instructions

Hey 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

RequirementMinimum VersionNotes
WindowsWindows 10 or 1164-bit recommended
PowerShellVersion 5.1 or higherPowerShell 7 recommended
Internet ConnectionStable broadbandRequired for API calls
Web BrowserEdge, Chrome, or FirefoxFor Azure Portal access

Access Requirements

Access TypeWhy You Need It
Azure Portal AccessTo create the App Registration that authenticates our script
Global Admin or Cloud App AdminTo grant admin consent for API permissions
Power Platform AdminTo create Application User and access environments
Copilot Studio LicenseYou need at least one environment with Copilot Studio agents
💡 TIP
If you don't have admin access, ask your IT administrator to help with the Azure and Power Platform setup steps.

🔐 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

1 Open your web browser and go to https://portal.azure.com
2 Sign in with your work or school account
3 In the search bar at the top, type App registrations and click on it
4 Click the + New registration button at the top
5 Fill in the registration form:
  • 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)
6 Click the Register button

Step 2.2: Copy Your IDs (IMPORTANT!)

After registration, you'll see the Overview page. You need to copy TWO important values:

What to CopyWhat It's Called in the Script
Application (client) IDThis is your $ClientId - looks like: xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx
Directory (tenant) IDThis is your $TenantId - looks like: xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx
📝 ACTION REQUIRED
Open Notepad and paste these two IDs. You'll need them when configuring the script!

Step 2.3: Create a Client Secret

The Client Secret is like a password for your app. Here's how to create one:

1 In your App Registration, click Certificates & secrets in the left menu
2 Click the Client secrets tab (it should be selected by default)
3 Click + New client secret
4 Enter a description: Copilot Export Script
5 Select an expiration: 12 months (recommended) or 24 months
6 Click Add
⚠️ CRITICAL
Copy the VALUE immediately! It will ONLY be shown once. If you miss it, you'll need to create a new secret.
7 Copy the Value column (NOT the Secret ID) - This is your $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 NameTypeWhat It Does
Reports.Read.AllApplicationAllows reading usage reports and Copilot data
User.Read.AllApplicationAllows looking up user names (for agent owners)
Directory.Read.AllApplicationAllows reading directory information (optional)

Step 3.1: Add the Permissions

1 In your App Registration, click API permissions in the left menu
2 Click + Add a permission
3 In the panel that opens, click Microsoft Graph
4 Click Application permissions (NOT Delegated permissions!)
5 In the search box, type Reports
6 Expand Reports and check the box for Reports.Read.All
7 Search for User and check User.Read.All
8 Click Add permissions at the bottom

Step 3.2: Grant Admin Consent

This is a crucial step! Without admin consent, the permissions won't work.

1 Back on the API permissions page, you'll see your newly added permissions
2 Click the Grant admin consent for [Your Organization] button
3 Click Yes in the confirmation dialog
4 Wait a few seconds - you should see green checkmarks ✓ appear next to each permission
✅ SUCCESS CHECK
All permissions should show "Granted for [Your Organization]" with green checkmarks. If not, contact your admin!

⚡ 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

1 Open a new browser tab
3 Sign in with your admin account

Step 4.2: Navigate to Your Environment

1 In the left menu, click Environments
2 Find and click on your environment (e.g., microsoft (default))
3 Click Settings in the top toolbar

Step 4.3: Create Application User

1 In the Settings page, expand Users + permissions
2 Click Application users
3 Click + New app user button
4 Click + Add an app
5 In the search box, paste your Application (client) ID from Part 2
6 Select your app from the results and click Add
7 For Business unit, select the root business unit
8 Click Edit security roles
9 Check the box for System Administrator
10 Click Save then Create
🔄 REPEAT FOR MULTIPLE ENVIRONMENTS
If you have multiple environments with Copilot agents, repeat this process for each environment!

📦 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 NameRequired?Purpose
Microsoft.PowerApps.Administration.PowerShell✅ RequiredConnect to Power Platform and discover environments
Microsoft.Xrm.Tooling.CrmConnector.PowerShell✅ RequiredConnect to Dataverse and query agent data

Step 5.1: Open PowerShell as Administrator

1 Click the Start button (Windows icon)
2 Type PowerShell
3 Right-click on Windows PowerShell and select Run as administrator
4 Click Yes when prompted

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 CurrentUser

Module 2: CRM Connector (Dataverse)

Install-Module Microsoft.Xrm.Tooling.CrmConnector.PowerShell -Force -Scope CurrentUser

If prompted to install from an untrusted repository, type Y and press Enter.

✅ SUCCESS
You should see both modules download and install. This may take 2-3 minutes total.
💡 VERIFY INSTALLATION
You can verify the modules are installed by running:
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

  1. Open Notepad (search for it in the Start menu)
  2. Copy the ENTIRE script below
  3. Paste it into Notepad
  4. Save the file as Export-CopilotStudioAgents.ps1 in C:\mcp\
📁 CREATE FOLDER FIRST
If the C:\mcp folder doesn't exist, create it! Right-click in C:\ drive → New → Folder → name it '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 NameReplace ThisWith This (Your Value)
$TenantIdYOUR_TENANT_ID_HEREYour Directory (tenant) ID from Azure
$ClientIdYOUR_CLIENT_ID_HEREYour Application (client) ID from Azure
$ClientSecretYOUR_CLIENT_SECRET_HEREYour 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

⬇️ COPY EVERYTHING BELOW ⬇️
<#
.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 ""
⬆️ COPY EVERYTHING ABOVE ⬆️

▶️ 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_HERE with your Tenant ID
  • Replaced YOUR_CLIENT_ID_HERE with your Client ID
  • Replaced YOUR_CLIENT_SECRET_HERE with your Client Secret
  • Created Application User in Power Platform (Part 4)
  • Installed both PowerShell modules (Part 5)

Execute the Script

1 Open PowerShell as Administrator
2 Navigate to the script folder:
cd C:\mcp
3 Run the script:
.\Export-CopilotStudioAgents.ps1
4 A browser window will open – sign in with your admin account
5 Wait for the script to complete (usually 30 seconds to 2 minutes)
6 The C:\mcp folder will open automatically with your CSV file!

🎉 What You'll Get

Your CSV file will contain these columns:

ColumnDescription
RankPosition in list (1 = most recently created)
AgentNameThe name of your Copilot Studio agent
OwnerWho created/owns the agent
StatusActive or Inactive
EnvironmentWhich Power Platform environment it's in
LanguageLanguage setting of the agent
CreatedOnWhen the agent was created
ModifiedOnWhen it was last modified
PublishedOnWhen it was last published
AgentIdUnique identifier (GUID)
SchemaNameInternal schema name
EnvironmentUrlDataverse 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

🔒 SECURITY REMINDER
Never share your Client Secret publicly! Treat it like a password. If you accidentally expose it, create a new one in Azure and delete the old one.

📋 Quick Reference Summary

ItemDetails
Azure PermissionsReports.Read.All, User.Read.All, Directory.Read.All
PowerShell ModulesMicrosoft.PowerApps.Administration.PowerShell
Microsoft.Xrm.Tooling.CrmConnector.PowerShell
Power Platform RoleSystem Administrator (for Application User)
Script LocationC:\mcp\Export-CopilotStudioAgents.ps1
Output LocationC:\mcp\CopilotStudioAgents_[timestamp].csv

Comments

Popular posts from this blog

Bridging the Impossible: Connecting Jira On-Prem to Power Automate & Copilot Studio — The Solution Nobody Built Until Now"

How I Automated My Entire SharePoint Tenant with 150 MCP Tools and Claude Desktop

Azure Management MCP Server