I have an Azure DevOps organization with more 300 project and I want to extract release from the org for all DevOps project. I have tried using below PowerShell script but it is just giving 100 record at a time. and also it is saying that extracted json file is not in valid format.
Here is my PowerShell script.
$token = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
$url = "https://dev.azure.com/{orgnization}/_apis/projects?api-version=6.0"
$token = [System.Convert]::ToBase64String([System.Text.Encoding]::ASCII.GetBytes(":$($token)"))
$response = Invoke-RestMethod -Uri $url -Headers #{Authorization = "Basic $token" } -Method Get -ContentType application/json
Foreach ($projectName in $response.value.name) {
$url1 = "https://vsrm.dev.azure.com/{orgnization}/$($projectname)/_apis/release/releases?api-version=6.0"
$response = Invoke-RestMethod -Uri $url1 -Headers #{Authorization = "Basic $token" } -Method Get -ContentType application/json-patch
echo $response | ConvertTo-Json -Depth 99 | Out-File "D:\\file.json" -Append
}
I tried adding $top parameter with first API call which works fine if I am trying in browser but in PowerShell it is not working.
https://dev.azure.com/uniperteamservices/_apis/projects?api-version=6.0&$top=500
How can I accomplish my below two requirement?
How can extract all record, not just 100
Why extracted json file is showing as invalid format when I am converting to excel?
If you can modify above PowerShell script for my requirement, it will be appreciated.
Thanks
Step through your code in a debugger.
$top wrapped in double quotes will try to interpolate a variable named $top. You need to escape the $ with a ` character. i.e.
`$top
Related
We have a task/job during our release pipeline that we would like to skip in the event that files haven't changed in a particular folder in our repo. I am able to get a powershell script task to change a variable to skip the following task properly, but I don't know how I can do the actual comparison to determine whether to skip or not.
How can I compare changes via git or some other way to see if files have changed in a particular folder since the last release? Is it possible to compare the current artifact to the last deployed artifact in some way?
Is it possible to compare the current artifact to the last deployed artifact in some way?
Yes. We can add a PowerShell task and run Rest APIs to compare the artifacts and get the changes files.
Here is an PowerShell example:
$token = "$(PAT)"
$url=" https://vsrm.dev.azure.com/OrgName/ProjectName/_apis/release/deployments?definitionId=releasedefinitionid&deploymentStatus=succeeded&definitionEnvironmentId=releasedefinitionenvironmentid&api-version=6.0"
$token = [System.Convert]::ToBase64String([System.Text.Encoding]::ASCII.GetBytes(":$($token)"))
$response = Invoke-RestMethod -Uri $url -Headers #{Authorization = "Basic $token"} -Method Get -ContentType application/json
echo $response.value[0].release.id
$lastreleaseid = $response.value[0].release.id
$url1 ="https://vsrm.dev.azure.com/OrgName/ProjectName/_apis/Release/releases/$(RELEASE.RELEASEID)/changes?baseReleaseId=$($lastreleaseid)&%24top=2500&artifactAlias=Artifacts Alias name&api-version=7.1-preview.1"
$response1 = Invoke-RestMethod -Uri $url1 -Headers #{Authorization = "Basic $token"} -Method Get -ContentType application/json
$count = 0
Foreach ($commitid in $response1.value.id)
{
echo $commitid
$url2 = "https://dev.azure.com/OrgName/_apis/git/repositories/RepoId/commits/$($commitid)/changes?api-version=7.0"
$response2 = Invoke-RestMethod -Uri $url2 -Headers #{Authorization = "Basic $token"} -Method Get -ContentType application/json
Foreach ($changefile in $response2.changes)
{
$filepath= $changefile.item.path
if($filepath -like '/test*')
{
$count = $count + 1
}
}
}
echo $count
if($count -gt 0 )
{
echo "##vso[task.setvariable variable=one]secondValue"
}
Explanation:
Step1: We can use the Rest API:Deployments - List to get the last successful Release of the Release environmen.
Step2: We can use the following Rest API to get the commits between two release.
Get https://vsrm.dev.azure.com/OrgName/ProjectName/_apis/Release/releases/currentreleaseid/changes?baseReleaseId=comparereleaseid&%24top=2500&artifactAlias=Artifacts Alias name&api-version=7.1-preview.1
Step3: We can get the changed files of the commits via the Rest API: Commits - Get Changes
Finally, we can set the Pipeline variable based on the result of the API response.
Result:
I want to add an Azure-DevOps query to a pipeline,
Is there an option to put a query in a yaml file?
If yes, how?
Thanks in advance.
I suppose that you could run a rest api for query via powershell script or something like that in a pipeline task to do it.
GET https://dev.azure.com/{organization}/{project}/_apis/wit/queries/{query}?api-version=7.0
Powershell Script
# Define organization base url, PAT and API version variables
$orgUrl = "https://dev.azure.com/{org}/{project}"
$pat = "{pat}"
$queryString = "api-version=7.0"
# Create header with PAT
$token = [System.Convert]::ToBase64String([System.Text.Encoding]::ASCII.GetBytes(":$($pat)"))
$header = #{authorization = "Basic $token"}
# Get the list of all projects in the organization
$projectsUrl = "$orgUrl/_apis/wit/queries/{query}?$queryString"
$result = Invoke-RestMethod -Uri $projectsUrl -Method Get -ContentType "application/json" -Headers $header | ConvertTo-Json | ConvertFrom-Json
write-host $result
If you are going to echo the specific element from the query result, you could modify the $result line with below
$result = Invoke-RestMethod -Uri $projectsUrl -Method Get -ContentType "application/json" -Headers $header | ConvertTo-Json | ConvertFrom-Json | Select-Object -ExpandProperty {your element}
write-host $result
You could also create a query with rest api, and with the similar powershell script to put into pipeline.
POST https://dev.azure.com/{organization}/{project}/_apis/wit/queries/{query}?api-version=7.0
I am trying to create a Powershell script create a new release using DevOps API.
I can see the pipeline information using invoke rest method but not able to trigger a pipeline. Can I get some assistance here.?
Thanks,
Venkatraman
It's not documented very well, but to start the release you have to update the status to inProgress.
$updateReleaseUri = "$($vrsmBaseUri)_apis/Release/releases/$($releaseId)/environments/$($environmentId)?api-version=6.0-preview"
$updateReleaseJsonBody = #{status = 'inProgress' }
$updateReleaseJsonBody = $updateReleaseJsonBody | ConvertTo-Json -Depth 100
Invoke-RestMethod -Uri $updateReleaseUri -Method Patch -Headers $headers -Body $updateReleaseJsonBody -ContentType 'application/json'
Ref: https://learn.microsoft.com/en-us/rest/api/azure/devops/release/releases/update-release-environment?view=azure-devops-rest-6.0
You can use the specific endpoint "Releases - Create" to trigger the release pipeline.
The required parameter you need to provide at least to this endpoint is the definitionId of the release pipeline that you want to trigger.
Below is the complete PowerShell script of a demo as reference. I have tested with this script, and it can work well as expected.
$pat = '{Personal Access Token}'
$base64AuthInfo = [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(("{0}:{1}" -f "", $pat)))
$headers = New-Object "System.Collections.Generic.Dictionary[[String],[String]]"
$headers.Add("Authorization", ("Basic {0}" -f $base64AuthInfo))
$headers.Add("Content-Type", "application/json")
$uri = "https://vsrm.dev.azure.com/{organization}/{project}/_apis/release/releases?api-version=6.0"
$body = '{ "definitionId": {definitionId} }'
Invoke-RestMethod -Uri $uri -Headers $headers -Body $body -Method POST | ConvertTo-Json -Depth 10
I need to run a powershell script in a function called by Jenkins. When calling this function, two other parameters/variables are included. This is a sample of my code:
powershell '''
$Headers = #{"ApiKey"="$env:myKey"}
$jsonBody = #{
varOne= '$env:params.varOne'
varTwo = '$env:params.varTwo'} | ConvertTo-Json -Depth 10
Invoke-RestMethod -Method Post -Uri "myUrl" -Headers $Headers -Body $jsonBody
'''
This is throwing a 'Bad Response' error. Note that if I hard code the values that are in the variable, the script works.
I also try to wrap the script with withEnv but I got the same issue:
withEnv(["varOne=${params.varOne}, varTwo=${params.varTwo}"]) {
powershell '''
$Headers = #{"ApiKey"="$env:myKey"}
$jsonBody = #{
varOne= '$env:params.varOne'
varTwo = '$env:params.varTwo'} | ConvertTo-Json -Depth 10
Invoke-RestMethod -Method Post -Uri "myUrl" -Headers $Headers -Body $jsonBody
'''
}
Finally, I know I could call these variables successfully if I was using double quote instead of single ones
powershell """
some ps1 script
"""
However, when I do that it says:
groovy.lang.MissingPropertyException: No such property: Headers
If you're going to template variables you need """ as I said in the question you deleted, but you need to escape the $ on non templated variables
powershell """
\$Headers = #{"ApiKey"="$env:myKey"}
\$jsonBody = #{
varOne= '$env:params.varOne'
varTwo = '$env:params.varTwo'} | ConvertTo-Json -Depth 10
Invoke-RestMethod -Method Post -Uri "myUrl" -Headers \$Headers -Body \$jsonBody
"""
I'm getting data back from an API for a system of ours using Powershell but it doesn't quite return it correctly. It is putting the data all under one header as seen below. I'm trying to extract the downloadLink part only
Tried converting to JSON to see if I could get anywhere else with it.
$token = ".."
$web = Invoke-RestMethod -uri $url -Method Get -Headers #{'Authorization' = $token}
echo $web
I get this as the outcome:
documents
---------
{#{documentName=Name.docx.pdf; downloadLink=https://app.xxx.com/api/docs/employees/111/shared/111}, {#{documentName=Name.docx.pdf; downloadLink=https://app.xxx.com/api/docs/employees/111/shared/111} ...
What I need to get is the downloadLink, but as it's all coming under the documents header I can't do a simple select or get on it.
Have you tried converting the results from JSON using ConvertFrom-Json? See the code example below.
Please note the change I made to the ContentType to the Invoke-RestMethod as well.
$token = ".."
$web = Invoke-RestMethod -uri $url -Method Get -ContentType "application/json" -Headers #{'Authorization' = $token}
$webResults = $web | ConvertFrom-Json
echo ($json | ConvertFrom-Json).downloadLink