Scheduling a Azure DevOps release using Powershell - powershell

I am able to trigger a Azure DevOps release using Rest API call. But when i tried to do it by adding the scheduling it is not working. The code i used is given below:
$PATtoken= 'PAT'
$token = [System.Convert]::ToBase64String([System.Text.Encoding]::ASCII.GetBytes(":$($PATtoken)"))
$header=#{authorization= "Basic $token" }
$defurl = "https://vsrm.dev.azure.com/Orgnization/Project/_apis/release/definitions/13?api-version=5.1"
$definition = Invoke-RestMethod -Uri $defurl -Method Get -Headers $header
$triggers = '
[{
"schedule": {
"timeZoneId": "India Standard Time",
"startHours": 20,
"startMinutes": 40,
"daysToRelease": 31
}
}]'
$definition | Add-Member -NotePropertyName "triggers" -NotePropertyValue (Convertfrom-Json $triggers) -Force
$json = #($definition) | ConvertTo-Json -Depth 99
$updatedef = Invoke-RestMethod -Uri $defurl -Method Put -Body $json -ContentType "application/json" -Headers $header
Write-Host ($updatedef.triggers | ConvertTo-Json -Depth 99)
But unfortunately the scheduling or triggering is not happening.

You can do it in this way:
...
$definition = Invoke-RestMethod -Uri $defurl -Method Get -Headers $header
$hash = #(
#{ triggerType="schedule";
schedule = #{"daysToRelease"="31";"timeZoneId"="India Standard Time";"startHours"="20";"startMinutes"="40"}
}
)
$definition.triggers = $hash
$json = $definition | ConvertTo-Json -Depth 99
Invoke-RestMethod -Uri $defurl -Method Put -Body $json -ContnetType application/json -Headers $header

You should not add schedule into triggers to configure the release pipeline schedule execute.
You can use Postman as test. See below pic:
Even I have configure the schedule script in request body, the response body still has no content in the trigger.
To set the schedule, you need apply above schedule script to schedules which is nested under environment. Also, you could using Fiddler to capture the records to confirm this by configuring the schedule release from UI.

Related

azure devops release pipeline , bulk edit

$Organization = "y"
$Project = "x"
$DefinitionID = "81"
$url = "https://dev.azure.com/$Organization/$Project/_apis/build/definitions/$DefinitionID?api-version=6.0"
Write-Host "URL: $url"
$pipeline = Invoke-RestMethod -Uri $url -Headers #{
Authorization = "Bearer $env:SYSTEM_ACCESSTOKEN"
}
Write-Host "Pipeline = $($pipeline | ConvertTo-Json -Depth 100)"
$pipeline.variables.v1030.value = "xyz"
####****************** update the modified object **************************
$json = #($pipeline) | ConvertTo-Json -Depth 99
$updatedef = Invoke-RestMethod -Uri $url -Method Put -Body $json -ContentType "application/json" -Headers #{Authorization = "Bearer $env:SYSTEM_ACCESSTOKEN"}
write-host "=========================================================="
Write-host "The value of Varialbe 'v1030' is updated to"
$updatedef.variables.v1030.value
error:
2022-03-17T13:05:24.9981259Z Invoke-RestMethod : {"$id":"1","innerException":null,"message":"Build pipeline
2022-03-17T13:05:24.9982421Z 81 was not found.","typeName":"Microsoft.TeamFoundation.Build.WebApi.Definition
2022-03-17T13:05:24.9982939Z NotFoundException, Microsoft.TeamFoundation.Build2.WebApi","typeKey":"Definitio
2022-03-17T13:05:24.9983313Z nNotFoundException","errorCode":0,"eventId":3000}
Hi I get this error in Logs,
I think I can not find the release pipeline number
The $ DefinitionID
I want to do it on 100 releases pipelines I'll wrap it with 'for' later, but first I want to see I can do on one

Schedule a Azure devops release in multiple timings

I am able to schedule the release using Rest API call . Is there any way to Queue it to run Multiple times.THe code i tried is given below.
$timinglist=#(1:30,2:30,3:30)
foreach($time in $timinglist)
{
$PATtoken= 'PAT'
Write-Host "Initialize Autnetication COntext" -ForegroundColor DarkBlue
$token = [System.Convert]::ToBase64String([System.Text.Encoding]::ASCII.GetBytes(":$($PATtoken)"))
$header=#{authorization= "Basic $token" }
$defurl = "https://vsrm.dev.azure.com/Organization/Project/_apis/release/definitions/13?api-version=5.1"
$definition = Invoke-RestMethod -Uri $defurl -Method Get -Headers $header
$hour=$time.Split(":")[0]
$minute=$time.Split(":")[1]
$hash = #(
#{
triggerType="schedule";
schedule = #{"daysToRelease"="31";"timeZoneId"="India Standard Time";"startHours"=$hour;"startMinutes"=$minute}
})
$definition.triggers = $hash
$json = #($definition) | ConvertTo-Json -Depth 99
$updatedef = Invoke-RestMethod -Uri $defurl -Method Put -Body $json -ContentType "application/json" -Headers $header
Write-Host ($updatedef.triggers | ConvertTo-Json -Depth 99)
}
My objective is to queue a release at 1:30 2:30 and 3:30 . But with the above code it is running only at 3:30 and other two are not happening.
You are overriding the triggers property every time you send the request.
So the last value wins over the old ones.
triggers property is an array of BuildTrigger, you don't need to execute 3 request, just one!
This is the triggers documentation.
EDIT:
I am not a powershell wizard but you should create an array of BuildTrigger object like this:
$hash = #(
#{
triggerType="schedule";
schedule = #{"daysToRelease"="31";"timeZoneId"="India Standard Time";"startHours"=$hour1;"startMinutes"=$minute1}
},
#{
triggerType="schedule";
schedule = #{"daysToRelease"="31";"timeZoneId"="India Standard Time";"startHours"=$hour2;"startMinutes"=$minute2}
},
#{
triggerType="schedule";
schedule = #{"daysToRelease"="31";"timeZoneId"="India Standard Time";"startHours"=$hour3;"startMinutes"=$minute3}
}
)

Create Release on GitLab with PowerShell

I try to create a powershell script which can help us to create a release on our private gitlab server.
I found this tutorial
How to create releases in GitLab?
I'm not able to figure out how I can replace the curl command with the powershell invoke-webrequest command.
I already tried multiple concepts for this. In our case we have some code files and create the package in the same repository. The package is included in the gitignore file. (That's fine for us)
Now I tried to do this
$body = #{'form'='file=#/our awesome app.app'}
Invoke-RestMethod -Headers #{ 'PRIVATE-TOKEN'='<mytoeken>' } -Uri https://scm.domain.net/api/v4/projects/19/uploads -Body $Body
Result:
Invoke-RestMethod : {"error":"file is invalid"}
Does anyone have a script for creating a gitlab release page with download and changelog with powershell.
I also tried release it but I'm not able to configure it for gitlab.
https://www.npmjs.com/package/release-it#gitlab-releases
Below is a collection of some PowerShell snippets I have written or used for this purpose. Maybe this can help some people. Can you not create the $Body in the script also - it looks like it fails create the content from the file?
# Provides code snippets for Windows Powershell to use Gitlabs API to do various tasks
# for example [ Issue management, Release creation etc.]
# https://docs.gitlab.com/ee/api/
# Variables
# modify with you own content
$glUrl = "http://<your-gitlab-url>"
$p = "3" # Project ID
$tag = "1.3" # Modify this to create/delete release ...
$token = "<EDIT_ME>" # Your access token (http://<your-gitlab-url>/profile/personal_access_tokens)
$projectsUrl = "$glUrl/api/v4/projects" # i.e. http://<your-gitlab-url>/api/v4/projects
$pUrl = "$projectsUrl/$p" # i.e. http://<your-gitlab-url>/api/v4/projects/3
$releaseUrl = "$pUrl/releases" # i.e. http://<your-gitlab-url>/api/v4/projects/3/releases
$artifactsUrl = "$pUrl/jobs/artifacts/$tag/download?job=build-standard" # i.e. Build artifacts created for $tag and the relevant job ("build-standard"; can be modified)
# Project List
$r = Invoke-RestMethod -Headers #{ 'PRIVATE-TOKEN'="$token" } -Uri $projectsUrl
$r | Sort-Object -Property id | Format-Table -Property id, name
# Issues List
$r = Invoke-RestMethod -Headers #{ 'PRIVATE-TOKEN'="$token" } -Uri $pUrl/issues
$r | Sort-Object -Property id | Format-Table -Property id, state, title
# New Issue
Invoke-RestMethod -Method Post -Headers #{ 'PRIVATE-TOKEN'="$token" } -Uri "$pUrl/issues?title=Hello from PS&labels=test"
# Comment on the Issue
Invoke-RestMethod -Method Post -Headers #{ 'PRIVATE-TOKEN'="$token" } -Uri "$pUrl/issues/3/notes?body=Hello PowerShell"
function Register-NewIssue {
param(
[string]$title,
[string]$desc = '',
[string]$uri = '$projectUrl/issues'
)
$title = [System.Web.HttpUtility]::UrlEncode($title)
$desc = [System.Web.HttpUtility]::UrlEncode($desc)
$u = "$uri`?title=$title&description=$desc"
$r = Invoke-RestMethod -Method Post -Headers #{ 'PRIVATE-TOKEN'= "$token" } -Uri $u
$r | Format-List -Property iid, state, title, description
}
# Get list of Releases
Invoke-RestMethod -Method Get -Headers #{ 'PRIVATE-TOKEN'="$token" } -Uri $releaseUrl
# Create a Release
$JSON = #"
{
"name": "New release",
"tag_name": $tag,
"ref": "master",
"description": "FromPS",
"assets":{
"links":[
{
"name":"Executables",
"url":"$artifactsUrl"
}
]
}
}
"#
Invoke-RestMethod -Method Post -Headers #{ 'PRIVATE-TOKEN'="$token"; 'Content-Type'='application/json' } -Body $JSON -Uri "$releaseUrl"
Read-Host -Prompt "Press Enter to continue"
# Adds only a link to this Release manually
$JSONLINK = #'
{"name":"awesome-exec",
"url":"$artifactsUrl"
}
'#
Invoke-RestMethod -Method Post -Headers #{ 'PRIVATE-TOKEN'= "$token"; 'Content-Type'='application/json' } -Body $JSONLINK -Uri "$releaseUrl/$tag/assets/links"
# Delete a Release
Invoke-RestMethod -Method Delete -Headers #{ 'PRIVATE-TOKEN'= "$token" } -Uri "$releaseUrl/$tag"

How can I cancel & delete a waiting build in the queue using PowerShell

Due to long running builds various next in line builds take longer time to execute.
Is there a way I can cancel and delete waiting build in queue and give way for latest triggered build using PowerShell or REST API's?
The following code snippet goes over all TFS builds,Gets the Builds which in Progress and not started, and then, cancel them.
$tfsUrl = "http://{server}:{port}/{organization}/{collection}/{project}" # TFS Base URL
$BuildDefsUrl = "$tfsUrl/_apis/build/definitions?api-version=2.0" # TFS build definitions URL
$BuildsUrl = "$tfsUrl/_apis/build/builds" #TFS Builds URL
$Builds = (Invoke-RestMethod -Uri ($BuildDefsUrl) -Method GET -UseDefaultCredentials).value | Select id,name # get all builds
#for filtering use : | Where-Object {$_.name -like "*Your Pattern*"}
foreach($Build in $Builds)
{
$command = "$($BuildsUrl)?api-version=3.2-preview.3&resultFilter=inprogress&definitions=$($Build.id)&queryOrder=finishTimeDescending"
$Ids = (((Invoke-RestMethod -Method Get -Uri $command -UseDefaultCredentials).value) | where status -like "*notStarted*").id # get waiting builds id's
foreach($id in $Ids)
{
$uri = "$($BuildsUrl)/$($id)?api-version=2.0" # TFS URI
$body = '{"status":4}' # body
$result = Invoke-RestMethod -Method Patch -Uri $uri -UseDefaultCredentials -ContentType 'application/json' -Body $body -Verbose #cancel build
}
}
The above example is pretty old. The code snippet below working for Azure Devops-
$PATToken = "PAT_GOES_HERE"
$AuthHeader= #{Authorization = 'Basic ' + [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(":$($PATToken)")) }
$azureDevops = "https://dev.azure.com/{organization}/{project}"
$BuildsUrl = "$azureDevops/_apis/build/builds"
$filterBuilds = "$($BuildsUrl)?statusFilter=notStarted&api-version=6.0"
(Invoke-RestMethod -Method Get -Uri $filterBuilds -Headers $AuthHeader).value | % {
$uri = "$($BuildsUrl)/$($_.id)?api-version=6.0" # Azure Devops URI
$body = '{"status":4}' # body
$result = Invoke-RestMethod -Method Patch -Uri $uri -Headers $AuthHeader -ContentType 'application/json' -Body $body -Verbose #cancel build
Write-Output "$($_.definition.name) cancaled"
}

Powershell Script does not wait for the response from Invoke-RestMethod cmdlet

I am new to powershell. I have a powershell script which basically makes an REST API request and gets back a JSON response. But I have an issue with the Invoke-RestMethod cmdlet. I mean the script sometimes doesn't wait for the response and continues with the next line of code.
Is there some trick in powershell which asks the code to wait for the API response and then run the remaining code. Below is my code
if ($EventID -eq '4726') {
$ad_user = "$TargetUsername#avayaaws.int"
$jsonbody = #{
"setupName" = "avayadev-or"
"instanceName" = "000_JumpServer_DMZ"
"command" = "$Command"
"parameters" = #{
"mobile" = "$getMobileAttr"
"ad_user"="$ad_user"
"label" ="$environment"
}
"eventToken" = "optional"
} | ConvertTo-Json
#$response = Start-Job {
# Invoke-RestMethod -Uri $uri -Method $verb -Body $jsonbody -Headers $header
#} | wait-job | receive-job
#$response = Invoke-RestMethod -Uri $uri -Method $verb -Body $jsonbody -Headers $header
$response = Invoke-WebRequest -Uri $uri -Method $verb -Body $jsonbody -Headers $header
$EventTrigger = $translEvent4726
Write-Output "Response is: $response"
PushLogs -transaction $EventTrigger -adUser $ad_user -transResult $response
}
I have tried many ways like using Out-Null and Wait-Job, Recieve-Job but couldn't get it to work. Any help is much appreciated.