Introduction
During a PowerShell session at my workplace, a colleague asked me an interesting question - How can I create work items in VSTS using PowerShell? This triggered me to share a TechNet wiki article. For me, Visual Studio Team Services was a foreign matter until I tried my hands on it to gain knowledge and experience.
Requirement
Team has a source file in CSV, XML, or JSON format and need an interface which connects to team project and create work items.
Solution
As a PowerShell enthusiast, I opted to use Visual Studio Team Services REST API with PowerShell to accomplish the task and selected Personal Access Token (PAT) authentication mechanism for demo purpose.
Create a Personal Access Token
- Sign in to either of your Visual Studio Team Services accounts (https://{youraccount}.visualstudio.com)
- From your home page, open your profile (hover on top your profile badge). Go to your security details.
- In the left pane, choose Personal Access Token.
- Click Add and name your token.
- Choose the life span for your token. Default is 90 days.
Convert Personal Access Token to Base64 String
With reference to the document, I developed a nifty PowerShell snippet shared below to convert the Personal Access Token to Base 64 string.
- $Token = "Personal Access Token"
- $Authentication = [Text.Encoding]::ASCII.GetBytes(":$Token")
- $Authentication = [System.Convert]::ToBase64String($Authentication)
- $Headers = @{
- Authorization = ("Basic {0}" -f $Authentication)
- }
- $Headers.Authorization
- 2/4
- # Output(Sample)
- Basic PAT1234ID=
REST API Endpoint URL
- PATCH https:ypeName}?api-version={version}
Sample Code
- $values = Import - csv C: \Source\ WIT.csv
- foreach($value in $values) {
- $RestParams = @ {
- Uri = "https://{account}/Automation/_apis/wit/workitems/`$product backlog item?apiversion=1.0"
- ContentType = 'application/json-patch+json'
- Headers = @ {
- Authorization = ("Basic {0}" - f $authentication)
- }
- Method = "Patch"
- Body = @(@ {
- op = "add"
- path = "/fields/System.Title"
- value = $value.value
- }
- @ {
- op = "add"
- path = "/fields/System.AreaPath"
- value = "Automation\Automation Scrum"
- }
- @ {
- op = "add"
- path = "/fields/System.IterationPath"
- value = "Automation\FY18-M01_JULY"
- }
- @ {
- op = "add"
- path = "/fields/System.AssignedTo"
- value = $value.technician
- }) | ConvertTo - Json
- }
- try {
- Invoke - RestMethod @RestParams - Verbose
- } catch {
- $_.Exception.Message
- }
- }