Examples.ps1

<#
.SYNOPSIS
    Example script demonstrating M365PlannerPro module usage
 
.DESCRIPTION
    This script contains practical examples of all M365PlannerPro module functions.
    Make sure you're connected to Microsoft Graph before running these examples.
 
.NOTES
    Author: Microsoft Planner Pro Team
    Version: 1.1.0
     
    Prerequisites:
    1. Connect-MgGraph -Scopes "Group.Read.All", "Tasks.ReadWrite", "User.Read.All"
    2. Replace example IDs with real IDs from your tenant
#>


# =============================================================================
# INITIAL SETUP
# =============================================================================

# Import the module
Import-Module "$PSScriptRoot\M365PlannerPro.psd1" -Force

# Verify Microsoft Graph connection
try {
    $context = Get-MgContext
    if (-not $context) {
        Write-Host "⚠️ You're not connected to Microsoft Graph" -ForegroundColor Yellow
        Write-Host "Run: Connect-MgGraph -Scopes 'Group.Read.All','Tasks.ReadWrite','User.Read.All'" -ForegroundColor Cyan
        exit
    }
    Write-Host "✅ Connected to Microsoft Graph as: $($context.Account)" -ForegroundColor Green
}
catch {
    Write-Error "Error verifying Microsoft Graph connection: $_"
    exit
}

# =============================================================================
# EXAMPLE 1: CLONE A COMPLETE PLAN
# =============================================================================

Write-Host "`n" + "="*80 -ForegroundColor Cyan
Write-Host "EXAMPLE 1: Clone a Planner Plan" -ForegroundColor Cyan
Write-Host "="*80 -ForegroundColor Cyan

# ⚠️ Replace these IDs with real values from your tenant
$sourceGroupId = "YOUR-SOURCE-GROUP-ID"        # Source group ID
$sourcePlanId = "YOUR-SOURCE-PLAN-ID"          # Plan ID to copy
$destinationGroupId = "YOUR-DESTINATION-GROUP-ID"  # Destination group ID

<#
# Uncomment and modify with your real IDs
Write-Host "`nCloning plan..." -ForegroundColor Yellow
 
$newPlan = Copy-M365PPlan -SourceGroupId $sourceGroupId `
                          -SourcePlanId $sourcePlanId `
                          -DestinationGroupId $destinationGroupId `
                          -NewPlanTitle "Cloned Plan - $(Get-Date -Format 'yyyy-MM-dd')" `
                          -Verbose
 
Write-Host "✅ Plan cloned successfully" -ForegroundColor Green
Write-Host " New Plan ID: $($newPlan.Id)" -ForegroundColor White
Write-Host " Title: $($newPlan.Title)" -ForegroundColor White
#>


Write-Host "ℹ️ Example commented - Configure real IDs to run" -ForegroundColor Yellow

# =============================================================================
# EXAMPLE 2: BULK IMPORT TASKS FROM CSV
# =============================================================================

Write-Host "`n" + "="*80 -ForegroundColor Cyan
Write-Host "EXAMPLE 2: Bulk Task Import from CSV" -ForegroundColor Cyan
Write-Host "="*80 -ForegroundColor Cyan

# ⚠️ Replace these IDs with real values from your tenant
$targetPlanId = "YOUR-PLAN-ID"      # Plan ID where to import
$targetGroupId = "YOUR-GROUP-ID"    # Group ID of the plan

<#
# Uncomment and modify with your real IDs
$csvPath = "$PSScriptRoot\example-tasks.csv"
 
Write-Host "`nImporting tasks from: $csvPath" -ForegroundColor Yellow
Write-Host "Target plan: $targetPlanId" -ForegroundColor Yellow
 
$importResult = Import-M365PTasksFromCsv -PlanId $targetPlanId `
                                         -CsvPath $csvPath `
                                         -GroupId $targetGroupId `
                                         -Verbose
 
Write-Host "`n✅ Import completed" -ForegroundColor Green
Write-Host " Total tasks: $($importResult.TotalTasks)" -ForegroundColor White
Write-Host " Successful: $($importResult.Succeeded)" -ForegroundColor Green
Write-Host " Failed: $($importResult.Failed)" -ForegroundColor $(if($importResult.Failed -gt 0){"Red"}else{"White"})
#>


Write-Host "ℹ️ Example commented - Configure real IDs to run" -ForegroundColor Yellow
Write-Host " Sample CSV file available at: $PSScriptRoot\example-tasks.csv" -ForegroundColor Cyan

# =============================================================================
# EXAMPLE 3: USER WORKLOAD REPORT
# =============================================================================

Write-Host "`n" + "="*80 -ForegroundColor Cyan
Write-Host "EXAMPLE 3: User Workload Analysis" -ForegroundColor Cyan
Write-Host "="*80 -ForegroundColor Cyan

Write-Host "`n📊 Generating workload report..." -ForegroundColor Yellow

# Option A: Report all accessible plans
Write-Host "`nOption A: Analyze all plans (may take time)" -ForegroundColor Cyan
<#
$workloadReport = Get-M365PUserWorkload -Verbose
 
if ($workloadReport) {
    Write-Host "`n✅ Report generated for $($workloadReport.Count) user(s)" -ForegroundColor Green
     
    # Show top 10 most loaded users
    Write-Host "`n🔥 Top 10 users with most tasks:" -ForegroundColor Yellow
    $workloadReport | Select-Object -First 10 | Format-Table DisplayName, Email, TotalTasks, PlansCount -AutoSize
     
    # Identify overloaded users (more than 20 tasks)
    $overloaded = $workloadReport | Where-Object { $_.TotalTasks -gt 20 }
    if ($overloaded) {
        Write-Host "`n⚠️ ALERT: $($overloaded.Count) overloaded user(s) (>20 tasks)" -ForegroundColor Red
        $overloaded | Format-Table DisplayName, Email, TotalTasks, PlansCount -AutoSize
    }
     
    # Export complete report
    $reportPath = "$PSScriptRoot\workload-report-$(Get-Date -Format 'yyyyMMdd-HHmmss').csv"
    $workloadReport | Export-Csv -Path $reportPath -NoTypeInformation
    Write-Host "📄 Report exported to: $reportPath" -ForegroundColor Green
}
else {
    Write-Host "ℹ️ No task assignments found" -ForegroundColor Yellow
}
#>


# Option B: Report for specific group (faster)
Write-Host "`nOption B: Analyze a specific group" -ForegroundColor Cyan
# $groupId = "YOUR-GROUP-ID"
# $workloadReport = Get-M365PUserWorkload -GroupId $groupId -Verbose

# Option C: Report for specific plan
Write-Host "`nOption C: Analyze a specific plan" -ForegroundColor Cyan
# $planId = "YOUR-PLAN-ID"
# $workloadReport = Get-M365PUserWorkload -PlanId $planId -Verbose

Write-Host "ℹ️ Examples commented - Uncomment the option you want to run" -ForegroundColor Yellow

# =============================================================================
# EXAMPLE 4: SMART TASK UPDATE
# =============================================================================

Write-Host "`n" + "="*80 -ForegroundColor Cyan
Write-Host "EXAMPLE 4: Task Update with ETag Control" -ForegroundColor Cyan
Write-Host "="*80 -ForegroundColor Cyan

# ⚠️ Replace with a real task ID
$taskId = "YOUR-TASK-ID"

<#
# Example 4.1: Update task title
Write-Host "`n📝 Updating task title..." -ForegroundColor Yellow
$result = Update-M365PTaskSmart -TaskId $taskId `
                                -Title "Updated Task - $(Get-Date -Format 'HH:mm:ss')" `
                                -Verbose
 
if ($result.Status -eq 'Success') {
    Write-Host "✅ Task updated in $($result.Attempts) attempt(s)" -ForegroundColor Green
}
else {
    Write-Host "❌ Error: $($result.Error)" -ForegroundColor Red
}
 
# Example 4.2: Mark task as complete
Write-Host "`n✓ Marking task as complete..." -ForegroundColor Yellow
$result = Update-M365PTaskSmart -TaskId $taskId -PercentComplete 100 -Verbose
 
# Example 4.3: Update multiple properties
Write-Host "`n🔧 Updating multiple properties..." -ForegroundColor Yellow
$result = Update-M365PTaskSmart -TaskId $taskId `
                                -PercentComplete 75 `
                                -Priority 3 `
                                -DueDateTime (Get-Date).AddDays(7) `
                                -MaxRetries 3 `
                                -Verbose
 
# Example 4.4: Bulk update with pipeline
Write-Host "`n⚡ Bulk update using pipeline..." -ForegroundColor Yellow
$planId = "YOUR-PLAN-ID"
 
Get-MgPlannerPlanTask -PlannerPlanId $planId -All |
    Where-Object { $_.Title -like "*Review*" -and $_.PercentComplete -lt 100 } |
    ForEach-Object {
        Write-Host "Updating: $($_.Title)" -ForegroundColor Cyan
        Update-M365PTaskSmart -TaskId $_.Id -PercentComplete 50 -Verbose
    }
#>


Write-Host "ℹ️ Examples commented - Configure real IDs to run" -ForegroundColor Yellow

# =============================================================================
# EXAMPLE 5: COMPLETE WORKFLOW - NEW PROJECT SETUP
# =============================================================================

Write-Host "`n" + "="*80 -ForegroundColor Cyan
Write-Host "EXAMPLE 5: Complete Workflow - New Project Setup" -ForegroundColor Cyan
Write-Host "="*80 -ForegroundColor Cyan

<#
# This example shows a complete workflow
Write-Host "`n🚀 Starting new project setup..." -ForegroundColor Yellow
 
# Step 1: Clone a template plan
Write-Host "`n[1/4] Cloning template plan..." -ForegroundColor Cyan
$templateGroupId = "TEMPLATE-GROUP-ID"
$templatePlanId = "TEMPLATE-PLAN-ID"
$projectGroupId = "PROJECT-GROUP-ID"
 
$newProjectPlan = Copy-M365PPlan -SourceGroupId $templateGroupId `
                                 -SourcePlanId $templatePlanId `
                                 -DestinationGroupId $projectGroupId `
                                 -NewPlanTitle "Q1 2026 Project" `
                                 -Verbose
 
Write-Host "✅ Plan created: $($newProjectPlan.Title)" -ForegroundColor Green
 
# Step 2: Import additional project-specific tasks
Write-Host "`n[2/4] Importing custom tasks..." -ForegroundColor Cyan
$importResult = Import-M365PTasksFromCsv -PlanId $newProjectPlan.Id `
                                         -CsvPath "$PSScriptRoot\example-tasks.csv" `
                                         -GroupId $projectGroupId `
                                         -Verbose
 
Write-Host "✅ Imported $($importResult.Succeeded) tasks" -ForegroundColor Green
 
# Step 3: Adjust project dates (extend 7 days)
Write-Host "`n[3/4] Adjusting project dates..." -ForegroundColor Cyan
Get-MgPlannerPlanTask -PlannerPlanId $newProjectPlan.Id -All |
    Where-Object { $_.DueDateTime } |
    ForEach-Object {
        $newDueDate = ([DateTime]$_.DueDateTime).AddDays(7)
        Update-M365PTaskSmart -TaskId $_.Id -DueDateTime $newDueDate
    }
 
Write-Host "✅ Dates adjusted" -ForegroundColor Green
 
# Step 4: Generate initial workload report
Write-Host "`n[4/4] Generating initial workload report..." -ForegroundColor Cyan
$initialWorkload = Get-M365PUserWorkload -PlanId $newProjectPlan.Id
 
$reportPath = "$PSScriptRoot\project-workload-initial.csv"
$initialWorkload | Export-Csv -Path $reportPath -NoTypeInformation
 
Write-Host "✅ Report generated: $reportPath" -ForegroundColor Green
Write-Host "`n🎉 Project setup completed successfully!" -ForegroundColor Green
#>


Write-Host "ℹ️ Example commented - Configure real IDs to run" -ForegroundColor Yellow

# =============================================================================
# EXAMPLE 5: EXPORT AND BACKUP PLANS
# =============================================================================

Write-Host "`n" + "="*80 -ForegroundColor Cyan
Write-Host "EXAMPLE 5: Export and Backup Plans" -ForegroundColor Cyan
Write-Host "="*80 -ForegroundColor Cyan

<#
# ⚠️ Replace with real IDs
$planToBackup = "YOUR-PLAN-ID"
 
# Create backup directory
$backupDir = "$PSScriptRoot\Backups"
if (-not (Test-Path $backupDir)) {
    New-Item -Path $backupDir -ItemType Directory | Out-Null
}
 
# Export to JSON (default format)
Write-Host "`n[1/3] Exporting plan to JSON..." -ForegroundColor Cyan
Export-M365PPlan -PlanId $planToBackup `
                 -OutputPath "$backupDir\plan-backup-$(Get-Date -Format 'yyyyMMdd-HHmmss').json" `
                 -Verbose
 
Write-Host "✅ JSON backup completed" -ForegroundColor Green
 
# Export to XML with completed tasks
Write-Host "`n[2/3] Exporting plan to XML (with completed tasks)..." -ForegroundColor Cyan
Export-M365PPlan -PlanId $planToBackup `
                 -OutputPath "$backupDir\plan-backup-complete.xml" `
                 -Format XML `
                 -IncludeCompleted `
                 -Force `
                 -Verbose
 
Write-Host "✅ XML backup completed" -ForegroundColor Green
 
# Export all plans from a group
Write-Host "`n[3/3] Exporting all plans from a group..." -ForegroundColor Cyan
$groupId = "YOUR-GROUP-ID"
$groupPlans = Get-MgGroupPlannerPlan -GroupId $groupId
 
$groupBackupDir = "$backupDir\Group-$(Get-Date -Format 'yyyyMMdd')"
New-Item -Path $groupBackupDir -ItemType Directory -Force | Out-Null
 
foreach ($plan in $groupPlans) {
    $fileName = "$($plan.Title -replace '[\\/:*?"<>|]', '_').json"
    Export-M365PPlan -PlanId $plan.Id -OutputPath "$groupBackupDir\$fileName"
    Write-Host " ✓ Exported: $($plan.Title)" -ForegroundColor Gray
}
 
Write-Host "✅ Group backup completed: $($groupPlans.Count) plans" -ForegroundColor Green
#>


Write-Host "ℹ️ Example commented - Configure real IDs to run" -ForegroundColor Yellow

# =============================================================================
# EXAMPLE 6: IMPORT AND RESTORE PLANS
# =============================================================================

Write-Host "`n" + "="*80 -ForegroundColor Cyan
Write-Host "EXAMPLE 6: Import and Restore Plans" -ForegroundColor Cyan
Write-Host "="*80 -ForegroundColor Cyan

<#
# ⚠️ Replace with real values
$backupFile = "$PSScriptRoot\Backups\plan-backup.json"
$targetGroupId = "TARGET-GROUP-ID"
 
# Basic restore
Write-Host "`n[1/3] Restoring plan from backup..." -ForegroundColor Cyan
$restoredPlan = Import-M365PPlan -InputPath $backupFile `
                                 -GroupId $targetGroupId `
                                 -Verbose
 
Write-Host "✅ Plan restored: $($restoredPlan.Title)" -ForegroundColor Green
 
# Restore with custom title
Write-Host "`n[2/3] Importing plan as template..." -ForegroundColor Cyan
$templatePlan = Import-M365PPlan -InputPath $backupFile `
                                 -GroupId $targetGroupId `
                                 -PlanTitle "Project Template 2026" `
                                 -SkipDates `
                                 -Verbose
 
Write-Host "✅ Template created: $($templatePlan.Title)" -ForegroundColor Green
 
# Cross-tenant migration (structure only)
Write-Host "`n[3/3] Cross-tenant migration..." -ForegroundColor Cyan
$migratedPlan = Import-M365PPlan -InputPath $backupFile `
                                 -GroupId $targetGroupId `
                                 -SkipAssignments `
                                 -SkipDates `
                                 -PlanTitle "Migrated Plan" `
                                 -Verbose
 
Write-Host "✅ Plan migrated (structure only): $($migratedPlan.Title)" -ForegroundColor Green
Write-Host "ℹ️ Assignments and dates were skipped for cross-tenant compatibility" -ForegroundColor Yellow
#>


Write-Host "ℹ️ Example commented - Configure real IDs to run" -ForegroundColor Yellow

# =============================================================================
# EXAMPLE 7: COMPLETE BACKUP AND RESTORE WORKFLOW
# =============================================================================

Write-Host "`n" + "="*80 -ForegroundColor Cyan
Write-Host "EXAMPLE 7: Complete Backup and Restore Workflow" -ForegroundColor Cyan
Write-Host "="*80 -ForegroundColor Cyan

<#
# Scenario: Weekly backup routine for all critical plans
 
$criticalPlans = @(
    @{ GroupId = "GROUP-1-ID"; PlanId = "PLAN-1-ID"; Name = "ProjectAlpha" },
    @{ GroupId = "GROUP-2-ID"; PlanId = "PLAN-2-ID"; Name = "ProjectBeta" }
)
 
$weeklyBackupDir = "$PSScriptRoot\Backups\Weekly-$(Get-Date -Format 'yyyy-MM-dd')"
New-Item -Path $weeklyBackupDir -ItemType Directory -Force | Out-Null
 
Write-Host "`nStarting weekly backup routine..." -ForegroundColor Cyan
 
foreach ($plan in $criticalPlans) {
    try {
        Write-Host "`n Backing up: $($plan.Name)..." -ForegroundColor Gray
         
        Export-M365PPlan -PlanId $plan.PlanId `
                        -OutputPath "$weeklyBackupDir\$($plan.Name).json" `
                        -IncludeCompleted `
                        -Force
         
        Write-Host " ✓ Backup completed: $($plan.Name)" -ForegroundColor Green
    }
    catch {
        Write-Host " ✗ Failed to backup $($plan.Name): $_" -ForegroundColor Red
    }
}
 
Write-Host "`n✅ Weekly backup routine completed!" -ForegroundColor Green
Write-Host "📁 Backups saved to: $weeklyBackupDir" -ForegroundColor Cyan
 
# Cleanup old backups (keep last 4 weeks)
$allBackups = Get-ChildItem -Path "$PSScriptRoot\Backups" -Directory |
              Where-Object { $_.Name -like "Weekly-*" } |
              Sort-Object CreationTime -Descending
 
if ($allBackups.Count -gt 4) {
    Write-Host "`n🗑️ Cleaning up old backups..." -ForegroundColor Yellow
    $allBackups | Select-Object -Skip 4 | ForEach-Object {
        Remove-Item -Path $_.FullName -Recurse -Force
        Write-Host " Removed: $($_.Name)" -ForegroundColor Gray
    }
}
#>


Write-Host "ℹ️ Example commented - Configure real IDs to run" -ForegroundColor Yellow

# =============================================================================
# ADDITIONAL INFORMATION
# =============================================================================

Write-Host "`n" + "="*80 -ForegroundColor Cyan
Write-Host "ADDITIONAL INFORMATION" -ForegroundColor Cyan
Write-Host "="*80 -ForegroundColor Cyan

Write-Host "`n📚 For detailed help on each function:" -ForegroundColor Yellow
Write-Host " Get-Help Copy-M365PPlan -Full" -ForegroundColor White
Write-Host " Get-Help Export-M365PPlan -Full" -ForegroundColor White
Write-Host " Get-Help Import-M365PPlan -Full" -ForegroundColor White
Write-Host " Get-Help Import-M365PTasksFromCsv -Examples" -ForegroundColor White
Write-Host " Get-Help Get-M365PUserWorkload -Detailed" -ForegroundColor White
Write-Host " Get-Help Update-M365PTaskSmart -Full" -ForegroundColor White

Write-Host "`n📖 Complete documentation available at:" -ForegroundColor Yellow
Write-Host " $PSScriptRoot\README.md" -ForegroundColor White

Write-Host "`n🔗 Useful resources:" -ForegroundColor Yellow
Write-Host " • Microsoft Graph Planner API: https://learn.microsoft.com/graph/api/resources/planner-overview" -ForegroundColor White
Write-Host " • Microsoft.Graph.Planner Module: https://learn.microsoft.com/powershell/module/microsoft.graph.planner/" -ForegroundColor White

Write-Host "`n✨ Thanks for using M365PlannerPro!" -ForegroundColor Green
Write-Host ""