I was searching and searching and couldn’t find any good documentation on how to create & delete VSTS Projects with PowerShell – so I figured I would write some myself! There’s some great documentation on leveraging the VSTS Rest API, you can find it here: https://docs.microsoft.com/en-us/rest/api/vsts/ . The difficulty was translating the Rest API into something that’s we can call via PowerShell.
Here are the two relevant Rest APIs to use:
- Create Project Rest API: [POST] https://{accountName}.visualstudio.com/_apis/projects?api-version=4.1
- Delete Project Rest API: [DELETE] https://{accountName}.visualstudio.com/_apis/projects/{projectId}?api-version=4.1
Call VSTS Rest APIs
The first thing that’s needed when calling the Rest APIs is to obtain a Personal Access Token (PAT), you can do this right in the VSTS Portal. Once we have the PAT token, we can construct the headers for the Rest API call. It looks like this:
$PatToken = "<YOUR PERSONAL ACCESS TOKEN" # Base64-encodes the Personal Access Token (PAT) appropriately $base64AuthInfo = [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes((":$PatToken"))) $headers = @{Authorization=("Basic {0}" -f $base64AuthInfo)}
Create a New VSTS Project
Full Script Located in GitHub! https://github.com/petehauge/personal/blob/master/Scripts/VSTS/New-TeamProject.ps1
Here are the details on how to call the Create Project Rest API. See the link above for the full script!
$uri = "https://$ExistingAccountName.visualstudio.com/_apis/projects?api-version=4.1" $body=@" { "name": "$NewProjectName", "description": "Team Project created automatically for $NewProjectName team cloud", "capabilities": { "versioncontrol": { "sourceControlType": "Git" }, "processTemplate": { templateTypeId: "ADCC42AB-9882-485E-A3ED-7678F01F66BC" } } } "@ # Make the call to queue up a project creation $result = Invoke-RestMethod -Uri $uri -Method Post -ContentType "application/json" -Headers $headers -Body $body
Delete Project
Full Script Located in GitHub! https://github.com/petehauge/personal/blob/master/Scripts/VSTS/Remove-TeamProject.ps1
Deleting a project follows a similar pattern (many of the VSTS Rest APIs use the same pattern), although there is no body to specify in the request. Here are the details:
$deleteUri = "https://$ExistingAccountName.visualstudio.com/_apis/projects/$($existingProject.id)?api-version=4.1" # Make the call to delete the project $result = Invoke-RestMethod -Uri $deleteUri -Method Delete -ContentType "application/json" -Headers $headers
Comment below with any comments, suggestions or improvements!