如何在 Powershell 中使用 Microsoft Graph 获取 Planner 任务受让人?

问题描述 投票:0回答:1

我正在构建一个脚本,用于将任务从一个计划复制到另一个计划。 最终脚本的目的是将旧任务复制到新计划并在原始计划中删除它们,但现在我只是在复制任务。

我已成功复制任务标题、截止日期和完成百分比,但未能获取其他内容,例如受让人、注释、附件和存储桶。运行任务时,我在控制台中有一些输出,例如任务:

“任务测试任务 X 有受让人:”

“测试任务 X 的受让人信息未找到或不完整。”

“任务测试任务 X 没有附件。”

“任务测试任务 X 没有存储桶。”

“任务已移动:测试任务 X”

# PowerShell script to copy planner tasks from one plan to another
# You will need to connect to Microsoft Graph

# Define your variables
$tenant = "" # Your tenant ID
$clientid = "" # Your registered application client ID
$thumbprint = "" # Thumbprint of your registered application certificate
$sourcePlanId = "" # ID of the source plan from which tasks will be copied
$destinationPlanId = "" # ID of the destination plan where tasks will be copied to

# Connect to Microsoft Graph 
Connect-MgGraph -ClientId $clientid -TenantId $tenant -CertificateThumbprint $thumbprint

# Function to retrieve user details by ID
function Get-MgUserById {
    param (
        [string]$UserId
    )

    if (-not [string]::IsNullOrWhiteSpace($UserId)) {
        return Get-MgUser -UserId $UserId
    }
    else {
        Write-Warning "User ID is empty or null."
        return $null
    }
}

# Get top 3 tasks from the source plan
$sourceTasks = Get-MgPlannerPlanTask -PlannerPlanId $sourcePlanId -Top 3

# Initialize counter for moved tasks
$movedTasksCount = 0

# Iterate through each task in the source plan
foreach ($task in $sourceTasks) {
    # Initialize array to store assignees
    $assignees = @()
    
    # Check if task has assignees
    if ($task.Assignments) {
        Write-Host "Task $($task.Title) has assignees:"
        # Retrieve user details for each assignee and add them to the new task JSON
        foreach ($assignment in $task.Assignments) {
            $userId = $assignment.assignedUser.id
            if (-not [string]::IsNullOrEmpty($userId)) {
                Write-Host "Assignee User ID: $userId"
                Write-Host $assignment | Format-List
                $assignees += @{
                    "assignedDateTime" = $null  # Add assignedDateTime if available
                    "orderHint"        = "string"  # Provide the order hint value
                    "assignedBy"       = @{
                        "user" = @{
                            "id" = $userId
                        }
                    }
                }
            }
            else {
                Write-Host "Assignee information not found or incomplete for $($task.Title)."
            }
        }
    }
    else {
        Write-Host "Task $($task.Title) has no assignees."
    }

    # Get task attachments
    $attachments = @()
    if ($task.Attachments) {
        Write-Host "Task $($task.Title) has attachments:"
        foreach ($attachment in $task.Attachments) {
            Write-Host "Attachment Name: $($attachment.Name)"
            $attachments += @{
                "name" = $attachment.Name
                "type" = $attachment.ContentType
                "url"  = $attachment.Url
            }
        }
    }
    else {
        Write-Host "Task $($task.Title) has no attachments."
    }

    # Get the bucket ID of the task in the destination plan
    $destinationTask = Get-MgPlannerPlanTask -PlannerPlanId $destinationPlanId -Top 1
    $bucketId = $destinationTask.BucketId

    if (-not [string]::IsNullOrWhiteSpace($bucketId)) {
        Write-Host "Task $($task.Title) has a bucket with ID: $bucketId"
    }
    else {
        Write-Host "Task $($task.Title) does not have a bucket."
    }

    # Create a JSON object representing the task to be added to the destination plan
    $newTaskJson = @{
        "planId"          = $destinationPlanId
        "title"           = $task.Title
        "labels"          = $task.Labels  # Retain task labels
        "percentComplete" = $task.PercentComplete
        "priority"        = $task.Priority  # Retain task priority
        "startDateTime"   = $task.StartDateTime
        "dueDateTime"     = $task.DueDateTime
        "notes"           = $task.Details.Description
        "bucketId"        = $bucketId  # Use the fetched bucket ID
        "attachments"     = $attachments  # Retain task attachments
        "assignments"     = $assignees  # Include assignees
        # Add other task details as needed
    }

    # Make a POST request to create the task in the destination plan
    $response = New-MgPlannerTask -Body ($newTaskJson | ConvertTo-Json -Depth 10)

    # Check if task was moved successfully
    if ($response) {
        Write-Host "Task moved: $($task.Title)"
        $movedTasksCount++
        
        # Delete the task from the source plan
        # Commented out for now
        # Remove-MgPlannerTask -PlannerTaskId $task.Id
    }
    else {
        Write-Host "Failed to move task: $($task.Title)"
    }
}

# Display total number of tasks moved
Write-Host "Total tasks moved: $movedTasksCount"

我尝试运行脚本,它复制了任务,但 Planner 中的源任务中不存在受让人、附件或相关存储桶

我是 PowerShell 和 Graph 的新手,因此即使只是为了解决如何复制任务的受让人的问题,任何见解都将不胜感激。

谢谢你。

powershell microsoft-graph-api microsoft-planner microsoft-graph-plannertasks
1个回答
0
投票

一位同事帮助我弄清楚受让人位于双层嵌套字典中,所以我肯定在这方面有帮助,但发布答案以防它对其他人有帮助。我还没有使用它来处理与计划任务相关的附件或注释。

# PowerShell script to copy planner tasks from one plan to another
# You will need to connect to Microsoft Graph

# Define my variables
$tenant = "" # Your tenant ID
$clientid = "" # Your registered application client ID
$thumbprint = "" # Thumbprint of your registered application certificate
$sourcePlanId = "" # ID of the source plan from which tasks will be copied
$destinationPlanId = "" # ID of the destination plan where tasks will be copied to

# Connect to Microsoft Graph 
Connect-MgGraph -ClientId $clientid -TenantId $tenant -CertificateThumbprint $thumbprint

# Get tasks from the source plan
$sourceTasks = Get-MgPlannerPlanTask -PlannerPlanId $sourcePlanId

# Initialize counter for created tasks
$createdTasksCount = 0

# Iterate through each task in the source plan
foreach ($task in $sourceTasks) {
    Write-Host "Processing task: $($task.Title)"

    # Fetch task details including the ETag
    $taskDetails = Get-MgPlannerTask -PlannerTaskId $task.Id
   
    # Extract the ETag value from the task details
    $etag = $taskDetails.'@odata.etag'

    # Get task attachments
    $attachments = @()
    if ($task.Attachments) {
        foreach ($attachment in $task.Attachments) {
            $attachments += @{
                "name" = $attachment.Name
                "type" = $attachment.ContentType
                "url" = $attachment.Url
            }
        }
    }

    # Get the bucket ID of the task in the destination plan
    $destinationTask = Get-MgPlannerPlanTask -PlannerPlanId $destinationPlanId -Top 1
    $bucketId = $destinationTask.BucketId

    # Construct the JSON object representing the task to be added to the destination plan
    $newTaskJson = @{
        "planId"         = $destinationPlanId
        "title"          = $task.Title
        "labels"         = $task.Labels
        "percentComplete"= $task.PercentComplete
        "priority"       = $task.Priority
        "startDateTime"  = $task.StartDateTime
        "dueDateTime"    = $task.DueDateTime
        "notes"          = $task.Details.Description
        "bucketId"       = $bucketId
        "attachments"    = $attachments
    }

    # Check if task has assignees
    if ($taskDetails.Assignments) {
        Write-Host "Assignees found for $($task.Title)"
       
        # Create a list to store assignee IDs for the current task
        $assigneeIds = @()

        # Loop through each assignment in the Assignments property
        foreach ($assignmentKey in $taskDetails.Assignments.PSObject.Properties) {
            foreach ($key in $assignmentKey.Value.Keys) {
                $assigneeIds += $key
            }
        }

        # Add assignments to the JSON object
        $assignments = @{}
        foreach ($assigneeId in $assigneeIds) {
            $assignments["$assigneeId"] = @{
                "@odata.type" = "microsoft.graph.plannerAssignment"
                "orderHint"   = " !"
            }
        }
        $newTaskJson["assignments"] = $assignments
    }

    # Make a POST request to create the task in the destination plan
    $response = New-MgPlannerTask -Body ($newTaskJson | ConvertTo-Json -Depth 10)

    # Check if task was created successfully
    if ($response) {
        Write-Host "Task created: $($task.Title)"
        $createdTasksCount++
    }
    else {
        Write-Host "Failed to create task: $($task.Title)"
    }
}

# Display total number of tasks created
Write-Host "Total tasks created: $createdTasksCount"
© www.soinside.com 2019 - 2024. All rights reserved.