PowerShell to Azure DevOps

Quick code snippet to connect to Azure DevOps using PowerShell.

What can this be used for?

For example, to export a list of Work Items returned by a query and save it somewhere.

Maybe you want to do the opposite, and create or update Work Items based on an input.

Or perhaps you would like to generate documentation based on your Work Items.

Obtaining a Personal Access Token (PAT)

The Personal Access Token is a simple mechanism to authenticate to Azure DevOps.
To get a PAT, follow the steps below.

1. Go to your Azure DevOps main page, click on the User Settings and the select the Personal Access Tokens button.

2. Click on the New Token button

3. Give the new Token a name, set an expiry date and tweak the permissions. For this example we will select only read Work Items.

4. Copy the access token and keep it in a safe place.

Code Explained

https://gist.github.com/crisfervil/3350912056303cae8158f085bc329f60#file-powershell-to-azure-devops-ps1

The code above does mainly tree things: Prepare parameters, execute a request, and do something with the results, in this case show them in the console.

1. Here is where you need to enter the PAT obtained in the previous section.

2. The organization and project names can be obtained from the URL you access when you open Azure DevOps in the browser.

3. There are several ways to query the data in Azure DevOps. One of them is to get the data returned by a query.

4. The PAT obtained must be added to the request header, but before doing so, it must be converted to the Base 64 format and placed it in the proper structure.

5. With the values provided in step 2, we build the URL we will be connecting to.

6. We use the Invoke-Rest method to perform an HTTP Request, passing the values previously prepared.

7. The results returned by the request is stored in a variable. This variable is an object containing the Work Items in the query, plus other information about the request and the query itself. In order to easily see what it contains, it can be converted to the JSON format and displayed on the screen.

Bonus

Find below examples of how to create a Task, and how to query Work Items using WIQL.

https://gist.github.com/crisfervil/8d2517915ea43e5db0cb425594b5f627

Wiql is the native language used by Azure DevOps to perform searches in the database.

https://gist.github.com/crisfervil/38866c3b0ac717476e82dc60f0bdc0ae

Conclusion

The code above doesn’t do much, but it shows the main steps to connect and retrieve data to Azure DevOps.

Is a basic tutorial I plan to reference in future articles.

I hope you find it useful. If you have any comments or queries, please leave them below.

Subscribe to our newsletter