How to Export a List of DevOps Commits using PowerShell

A short article today, covering how to export a csv list containing all recent commits to a DevOps project using PowerShell and the DevOps API.

This will require that you have an Azure DevOps token with read access to commits.

The Solution

$orgName = "" # The name of your DevOps Organisation
$projectName = "" # The name of the individual Project
$ErrorActionPreference = "Stop"
# You can get this by navigating to Project Settings > Repositories > Select a repository > Copy repo paramater from URL
$repositoryId = "69a47461-ffff-4a3a-gggg-ffffggggeeee" 

# Get PAT and create request Header
$personalAccessToken = Read-Host -Prompt "Enter the Personal Access Token for DevOps"
$token = [System.Convert]::ToBase64String([System.Text.Encoding]::ASCII.GetBytes(":$($personalAccessToken)"))
$header = @{authorization = "Basic $token"}

# Get a list of the top 500 commits
$request = Invoke-WebRequest -Headers $header -Uri "https://dev.azure.com/$orgName/$projectName/_apis/git/repositories/$repositoryId/commits?api-version=7.1-preview.1&`$`top=500" -Method GET -ContentType "application/json"
$requestContent = ($request.Content | ConvertFrom-Json).value

# Create an array containing just the commit comment and the date of the commit
$results = $requestContent | Select-Object comment,
   @{Name = "Date"; Expression = {$_.author.date}}

# Export then open a CSV file containing the data
$date = Get-Date
$results | export-csv -NoClobber -NoTypeInformation "C:\temp\latest-commits-$($date.Year)$($date.Month)$($date.Day)$($date.Millisecond).csv"
Invoke-item "C:\temp\latest-commits-$($date.Year)$($date.Month)$($date.Day)$($date.Millisecond).csv"

The code above is hopefully quite straightforward to understand and can be ran in Visual Studio Code or the PowerShell IDE, if you experience any issues trying to run it though don’t hesitate to comment below.

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.