I'm trying to get all the stale branches from Azure DevOps to nag the developers to remove them. If I use this script below, I get all the results I want, but it takes ages to process.
$resultlist = New-Object System.Collections.ArrayList
function Get-StaleBranches {
$dateString = (Get-Date).AddDays(-90).ToString("MM/dd/yyyy HH:mm:ss")
$date = [datetime]::parseexact($dateString, 'MM/dd/yyyy HH:mm:ss', $null)
$reposArray | ForEach-Object {
$repo = $PSItem
$refsUri = "url"
$refs = (Invoke-RestMethod -Uri $refsUri -Method get -Headers $AzureDevOpsAuthenicationHeader).value
foreach($branch in $refs){
$splitName = $branch.name.Substring(11)
$commitUri = $using:OrgUri + "url"
$commits = (Invoke-RestMethod -Uri $commitUri -Method get -Headers $AzureDevOpsAuthenicationHeader).value
$commitDate = [datetime]::parseexact($commits.author.date, 'MM/dd/yyyy HH:mm:ss', $null)
if($commitDate -lt $date -and $splitName -notlike "develop" -and $splitName -notlike "release" -and $splitName -notlike "master")
{
$result = @{}
$result.repo = $repo
$result.branch = $splitName
$result.date = $commitDate
$result.author = $commits.author.name
$result.email = $commits.author.email
$resultlist.Add((New-Object PsObject -Property $result)) | Out-Null
}
}
}
}
Get-StaleBranches
To speed it up, I tried using the foreach-object -parallel
functionality like this:
$threadSafeDictionary = [System.Collections.Concurrent.ConcurrentDictionary[string,object]]::new()
function Get-StaleBranches {
$dateString = (Get-Date).AddDays(-90).ToString("MM/dd/yyyy HH:mm:ss")
$date = [datetime]::parseexact($dateString, 'MM/dd/yyyy HH:mm:ss', $null)
$reposArray | ForEach-Object -Parallel {
$dict = $using:threadSafeDictionary
$repo = $PSItem
$dict.$repo = @()
$refsUri = "url"
$refs = (Invoke-RestMethod -Uri $refsUri -Method get -Headers $using:AzureDevOpsAuthenicationHeader).value
foreach($branch in $refs){
$splitName = $branch.name.Substring(11)
$commitUri = "url"
$commits = (Invoke-RestMethod -Uri $commitUri -Method get -Headers $using:AzureDevOpsAuthenicationHeader).value
$commitDate = [datetime]::parseexact($commits.author.date, 'MM/dd/yyyy HH:mm:ss', $null)
if($commitDate -lt $using:date -and $splitName -notlike "develop" -and $splitName -notlike "release" -and $splitName -notlike "master")
{
$dict.$repo += [PSCustomObject]@{
Branch = $splitName
Date = $commitDate
Author = $commits.author.name
Email = $commits.author.email
}
}
}
}
}
Get-StaleBranches
However, now all branches in the dictionary are doubled. Did I make a mistake somewhere? Is there any other way to approach this?
Any help will be appreciated.