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
"""
Related
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 attempting to use Powershell to perform some "POST" requests. However, I can't seem to get the JSON correctly formatted. How do I accomplish this?
>> $JSON=#{name:"TestName"}
>> Invoke-WebRequest -Uri http://localhost:7071/api/HttpTrigger1 -Method POST -Body $JSON
>> $response = Invoke-WebRequest -Uri "http://localhost:7071/api/HttpTrigger1" -Method Post -Body $JSON -ContentType "application/json"
ParserError:
Line |
1 | $JSON=#{name:"TestName"}
| ~
| Missing '=' operator after key in hash literal.
So, there are two ways you can do this:
The first, as suggested by Santiago, is
$json = '{name:"TestName"}'
$response = Invoke-WebRequest -Uri "http://localhost:7071/api/HttpTrigger1" `
-Method Post -Body $json -ContentType "application/json"
The second, using (roughly) the syntax you were using, is
#create a Powershell object (note the use of '=' instead of ':' for assignment)
#(such a simple example is not an improvement over the example above)
$json = #{ name = "TestName" } | ConvertTo-JSON
$response = Invoke-WebRequest -Uri "http://localhost:7071/api/HttpTrigger1" `
-Method Post -Body $json -ContentType "application/json"
The first method is certainly cleaner and more direct. The second is useful when the source data for the request comes as the result of manipulating Powershell objects, and you want to convert them for use in a web request.
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
Getting this error when trying to update a role to an endpoint using Powershell. It is crating the endpoints, just the roles update is giving error. same role update api call command works from postman.
$ApplyRole="https://Myorg/_apis/securityroles/scopes/distributedtask.serviceendpointrole/roleassignments/resources/72505f4d-564c-41cf-14508b977f52_f6a1c4f9-a043-4399-1aad7b5cf19c/?api-version=5.0-preview"
$ApplyRole = "https://Myorg/_apis/securityroles/scopes/distributedtask.serviceendpointrole/roleassignments/resources/72505f4d-564c-41cf-14508b977f52_f6a1c4f9-a043-4399-1aad7b5cf19c/?api-version=5.0-preview"
$Body1 = #{
roleName = "User"
userId = "f0e736e3-0e73-4fd2-8b7a-615126eac692"
}
$Bodyjson = $Body1 | ConvertTo-Json
Invoke-RestMethod -uri $ApplyRole -Method Put -Credential $mycreds -Body $Bodyjson -ContentType "application/json"
Error:
Invoke-RestMethod : {"$id":"1","innerException":null,"message":"Object reference not set to an instance of an object.","typeName":"System.NullReferenceException,
mscorlib","typeKey":"NullReferenceException","errorCode":0,"eventId":0}
Thanks for the reply.
Actually it was an issue with the body syntax.
Added like this and it works.
$Body1 = #"
[{
"roleName":"User",
"userId":"f0e736e3-0e73-4fd2-8b7a-615126eac692"
}]"#
Open pipeline definition->click the tab variables->add variable pat and change variable type to secret.
Add task powershell and enter the script.
$connectionToken="$(pat)"
$base64AuthInfo= [System.Convert]::ToBase64String([System.Text.Encoding]::ASCII.GetBytes(":$($connectionToken)"))
$ApplyRole = "https://Myorg/_apis/securityroles/scopes/distributedtask.serviceendpointrole/roleassignments/resources/{project id}_{endpoint id}/?api-version=5.0-preview"
$body ="[{
`"roleName`": `"User`",
`"userId`": `"{group or user id}`"
}]"
$Roles = Invoke-RestMethod -Uri $ApplyRole -ContentType "application/json" -Body $body -Headers #{Authorization=("Basic {0}" -f $base64AuthInfo)} -Method PUT
Result:
I have a simple build definition without build steps and with just a custom process variable.
Trying to update the variable through REST API with PowerShell:
$definition = Invoke-RestMethod -Method Get -Uri $url -UseDefaultCredentials
$definition.variables.aaa = "xxx"
$j = ConvertTo-Json -Depth 3 $definition
Invoke-RestMethod -Method Put -Uri $url -Body $j -ContentType "application/json" -UseDefaultCredentials
will cause the removal of the variable from the build definition.
You should update aaa's value bbb not the variable aaa itself.
$definition.variables.aaa.value = "xxx"