close.ps1

<#
.SYNOPSIS
Reads all stories at a certain time and changes them to the state of that time
 
.DESCRIPTION
 
.PARAMETER date
    The date the state is considered for
     
.EXAMPLE
    Check from 1st of july 2019
     
    .\updateTasksWithCompletedWork -date 2019-06-01
#>

[CmdletBinding(SupportsShouldProcess=$true)]
param(
   [Parameter(Mandatory=$true)]
   [ValidateSet('GuidNew','Rolsped')]
   [string] $devOps,
   [DateTime] $date = (Get-Date).AddDays(-2)
)

if($devOps -eq "GuidNew")
{
    $devOpsUrl = "https://guidnew.visualstudio.com"
    $devOpsUser = "ssc@guidnew.com";
    $devOpsPAT = "kfogxnqhrqbic4dlfxsbzkpxdyqfg5jjrzsjzupthrzqsyuvcs5q";
    [string[]] $projects = "Andritz-OrderMonitoring", "SOTRA2019", "VTU", "Opticon";
}
if($devOps -eq "Rolsped")
{
    $devOpsUrl = "https://dev.azure.com/rolsped"
    $devOpsUser = "ssc@guidnew.com";
    $devOpsPAT = "ateoabshksiwxc356agqdsgenleh3vbpe7xxgkl26tvha7t7naoq";
    
    [string[]] $projects = "TruckerApp";
}

$base64AuthInfo = [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(("{0}:{1}" -f $devOpsUser, $devOpsPAT)));

foreach($project in $projects)
{
    $devOpsCall = "${devOpsUrl}/_apis/wit/wiql?api-version=5.1"
    $content = ConvertTo-JSON( @{ query="Select [System.Id], [System.State] From WorkItems Where [System.WorkItemType] = 'User Story' and [System.State] = 'Closed' and [System.TeamProject] = '${project}' ASOF '12/12/19 5:00' "; });

    $returned = Invoke-RestMethod -Uri $devOpsCall -Method Post -Body $content -ContentType "application/json" -Headers @{Authorization=("Basic {0}" -f $base64AuthInfo)}
    Write-Output "Got $($returned.workItems.Count) Items at project ${project}";

    foreach($item in $returned.workItems)
    {
        $id = $item.id
        
        $devOpsGetCall = "${devOpsUrl}/_apis/wit/workitems/${id}?bypassRules=True&suppressNotifications=True&api-version=5.1";
        $current = Invoke-RestMethod -Uri $devOpsGetCall -Method Get -ContentType "application/json" -Headers @{Authorization=("Basic {0}" -f $base64AuthInfo)}
        $currentState = $current.Fields."System.State";

        if($currentState -ne "Closed")
        {
            Write-Output "Setting Item ${id} to Closed. Current is ${currentState}";
            $devOpsUpdateCall = "${devOpsUrl}/_apis/wit/workitems/${id}?bypassRules=True&suppressNotifications=True&api-version=5.1";
            $content="[ { 'op': 'add', 'path': '/fields/System.State', 'value': 'Closed' } ]";
            Invoke-RestMethod -Uri $devOpsUpdateCall -Method Patch -Body $content -ContentType "application/json-patch+json" -Headers @{Authorization=("Basic {0}" -f $base64AuthInfo)}
        }
    }
}