need help here: I have this api which i run in Postman (https://dev.azure.com/abc/Abc/_apis/build/builds/24169/workitems?api-version=4.1), I get result as
{
"count": 50,
"value": [
{
"id": "21610",
"url": "https://dev.azure.com/abc/_apis/wit/workItems/21610"
},
{
"id": "21606",
"url": "https://dev.azure.com/abc/_apis/wit/workItems/21606"
}]}
I need to call this in Powershell, and get a list of all IDs. I am doing this way but I am not getting anything..what wrong am I doing?
Function GET-RELEASEWIT {
$AzureDevOpsPAT ='psgklxbjircg5g5fda'
$AzureDevOpsAuthenicationHeader = #{Authorization = 'Basic ' + [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(":$($AzureDevOpsPAT)")) }
$uriAcc = "https://dev.azure.com/abc/ABC/_apis/build/builds/24169/workitems?api-version=4.1"
write-host $uriAcc
$responseRelW = Invoke-RestMethod -Uri $uriAcc -Method get -Headers $AzureDevOpsAuthenicationHeader
write-host $responseRelW
$BID = #()
$BID += $responseRelW.value.id
write-host "********START****************"
write-host $BID
}
I've tried the below and it works. Only difference I can see is that I've used UTF8.GetBytes instead of ASCII.GetBytes when converting the PAT token to a base64 string, which shouldn't cause any difference since the character mappings are the same.
$uri = "https://dev.azure.com/abc/ABC/_apis/build/builds/24169/workitems?api-version=4.1"
$AzureDevOpsPAT ='psgklxbjircg5g5fda'
$B64Pat = [Convert]::ToBase64String([System.Text.Encoding]::UTF8.GetBytes(":$AzureDevOpsPAT"))
$headers = #{ Authorization = "Basic $B64Pat" }
Invoke-RestMethod -Uri $uri -Headers $headers
Note the URI and PAT token are obviously different when I tested this, but this should work for you.
Related
I have powershell script which is creating annotated tag for commit in azure repos, but when I run this script in azure release pipeline I got error: "The combination of parameters is either not valid or not complete." When I make call from Postman with my credentials. its working. I also set repo permission Create Tag to Allow. Which permission I need for creating annotated tags with build user?
$createTagUrl= "$($env:SYSTEM_TEAMFOUNDATIONCOLLECTIONURI)$env:SYSTEM_TEAMPROJECT/_apis/git/repositories/$($env:BUILD_REPOSITORY_ID)/annotatedtags?api-version=6.0-preview.1"
Write-Host "createTagUrl=" $createTagUrl
$jsonObject = #"
{
"name": "$($env:RELEASE_RELEASENAME)-$(ENVIRONMENT)",
"taggedObject":{
"objectId": "$($env:BUILD_BUILDID)"
},
"message": "test"
}
"#
Write-Host "JsonObject: " $jsonObject
$json = #($jsonObject) | ConvertTo-Json -Depth 99
$createdTag = Invoke-RestMethod -Uri $createTagUrl -Method Post -Body $json -ContentType "application/json" -Headers #{Authorization = "Bearer $env:SYSTEM_ACCESSTOKEN"}
I can reproduce your issue:
The root cause is the code on your side is wrong.
This should works:
$headers = New-Object "System.Collections.Generic.Dictionary[[String],[String]]"
$headers.Add("Authorization", "Basic <PAT>")
$headers.Add("Content-Type", "application/json")
$body = "{
`n `"name`": `"xxx`",
`n `"message`": `"xxx`",
`n `"taggedObject`": {
`n `"objectId`": `"<object id>`"
`n }
`n}"
$response = Invoke-RestMethod 'https://dev.azure.com/<Organization Name>/<Project Name>/_apis/git/repositories/<Repo Name>/annotatedtags?api-version=4.1-preview.1' -Method 'POST' -Headers $headers -Body $body
$response | ConvertTo-Json
I want to tag a commit in azure devops git repo using the below POST call (in PowerShell script). API documentation here:
https://learn.microsoft.com/en-us/rest/api/azure/devops/git/annotated-tags/create?view=azure-devops-rest-6.0
{
"name": "v0.1-beta",
"taggedObject": {
"objectId": "c60be62ebf0e86b5aa01dbb98657b4b7e5905234"
},
"message": "First beta release"
}
So far I have written the below PowerShell script:
$Azuretoken = "xxxxxxxxxxxxxxxxxxxxxxxx"
$OrganizationName = "myorg"
$ProjectName = "myproj"
$AuthenicationHeader = #{Authorization = 'Basic ' + [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(":$($Azuretoken)")) }
$uri_tag = "https://dev.azure.com/$($OrganizationName)/$($ProjectName)/_apis/git/repositories/b27ea2df-a72f-45gdf/annotatedtags?api-version=6.0-preview.1"
$body = #(
"name"= "v0.1-beta",
"taggedObject" #{
"objectId" = "2fa9486683e3d3003fd58dbb9345aae3cdd21013"
},
"message" = "First beta release"
)
$uri = Invoke-RestMethod -Uri $uri_tag -Method POST -ContentType "application/json" -Body $body -Headers $AuthenicationHeader
Getting errors due to the format of the JSON. Please help.
Looks like $body isn't formatted correctly. Check out about_Hash_Tables.
$Azuretoken = "xxxxxxxxxxxxxxxxxxxxxxxx"
$OrganizationName = "myorg"
$ProjectName = "myproj"
$AuthenicationHeader = #{Authorization = 'Basic ' + [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(":$($Azuretoken)")) }
$uri_tag = "https://dev.azure.com/$($OrganizationName)/$($ProjectName)/_apis/git/repositories/b27ea2df-a72f-45gdf/annotatedtags?api-version=6.0-preview.1"
$body = #{
"name" = "v0.1-beta";
"taggedObject" = #{
"objectId" = "2fa9486683e3d3003fd58dbb9345aae3cdd21013"
};
"message" = "First beta release";
}
$uri = Invoke-RestMethod -Uri $uri_tag -Method POST -ContentType "application/json" -Body $body -Headers $AuthenicationHeader
I am trying to make an API call to update one devicegroup in each loop using the reference ID. I am able to fetch token but having issue when using PUT to update the devicegroup. Here is what i tried so far:
$Header1 = #{}
$Header1["Authorization"] = "Bearer " + $Token
try
{
#Using /devices to get the group level path as I am trying to update a customattribute on group level instead of each device
$response1 = Invoke-RestMethod -Uri "https://$MCFQDN/MobiControl/api/devices" -Headers $Header1
#Using /devicegroups for reference ID
$response2 = Invoke-RestMethod -Uri "https://$MCFQDN/MobiControl/api/devicegroups" -Headers $Header1
}
catch
{
$($_.Exception.Message)
}
foreach ($path1 in $response1)
{
foreach ($path2 in $response2)
{
if ($path1.Path -eq $path2.Path)
{
$refid = "referenceId:" + $path2.ReferenceId
#$refid = [System.Web.HttpUtility]::UrlEncode($refid) #tried encoding refid but no use
$uri = "https://$MCFQDN/MobiControl/api/devicegroups/$refid/customAttributes/{Custom_Attribute_Name}"
#This is the value for my Custom_Attribute_Name
$groupname = ($path2.Path).split('\')[-1]
$Body1 = #{}
$Body1["customAttributeValue"] = $groupname
# tried $Body1 = #{$groupname} but in vain
Invoke-RestMethod -Uri $uri -Method PUT -Body ($Body1 | ConvertTo-Json) -Headers $Header1 -ContentType "application/json"
}
}
}```
When trying to execute the above, getting below error:
*Invoke-RestMethod : {
"$type": "ErrorDetails",
"ErrorCode": 0,
"Message": "Contract validation failed",
"Data": [
"customAttributeValue: Error parsing value"
],
"HelpLink": null
}*
Any help is greatly appreciated.
Based off a brief test on the api page (https://FQDN/MobiControl/api). I receive the same “customAttributeValue: Error parsing value” error if I don’t quote the customAttributeValue value itself with single or double quotes. Try amending your $groupname variable with that in mind.
I am trying to use a REST API to configure some alerts in RecoverPoint for Virtual Machines (RP4VM). I am trying to enter multiple filters at the same using json. The json file looks like this:
[
{
"JsonSubType": "SystemEventLogsFilter",
"level": "WARNING",
"scope": "NORMAL",
"eventsIDs": [],
"filterUID": {
"id": 1570417688566256135
},
"name": "RPA_issue",
"topic": "RPA",
"groupsToInclude": null
},
{
"JsonSubType": "SystemEventLogsFilter",
"level": "WARNING",
"scope": "ADVANCED",
"eventsIDs": [],
"filterUID": {
"id": -1728986321682574312
},
"name": "cluster_events",
"topic": "CLUSTER",
"groupsToInclude": null
}
]
When I try to run the script I get an error:
Unexpected token (START_ARRAY), expected START_OBJECT: need JSON Object to contain As.PROPERTY type information (for class com.emc.fapi.version5_2.commons.SystemEventLogsFilter)
at [Source: org.apache.catalina.connector.CoyoteInputStream#75b592c2; line: 1, column: 1]
If I remove the square brackets it does the first value but not the second. Is this an issue with my code or an issue with theirs?
The script:
$rp4vmcl = import-csv -Path .\test_clusters.csv
$credential = Get-Credential
$username = $credential.GetNetworkCredential().UserName
$password = $credential.GetNetworkCredential().password
$credPair = "$($username):$($password)"
$encodedCredentials = [System.Convert]::ToBase64String([System.Text.Encoding]::ASCII.GetBytes($credPair))
$headers = #{
Authorization = "Basic $encodedCredentials";
"Accept" = "application/json";
"Content-Type" = "application/json"
}
$comp = "/system/event_logs_filters"
$json = Get-Content .\event_log_filter.json -Raw
foreach ($s in $rp4vmcl) {
$cluster = $s.cluster_name
$uid = $s.cluster_uid
$curl = $s.cluster_url
$url = "$curl$comp"
$cluster
$results = Invoke-RestMethod -Method POST -uri $url -SkipCertificateCheck -Headers $headers -Body $json
}
If the recipient expect one Call per Json Object it will not be able to handle arrays. It's totally dependant from the implementation of the webservice. Btw, better change the body:
$results = Invoke-RestMethod -Method POST -uri $url -SkipCertificateCheck -Headers $headers -Body ([System.Text.Encoding]::UTF8.GetBytes($json))
Try this first, and if this is doesnt help, loop through the elemnts and call the webservice individual:
$jsonObject = $json | ConvertFrom-Json
$results = #()
$jsonObject | foreach {
$json = $_ | ConvertTo-Json -Depth 99
$results += Invoke-RestMethod -Method POST -uri $url -SkipCertificateCheck -Headers $headers -Body ([System.Text.Encoding]::UTF8.GetBytes($json))
}
Btw, the invoke-restmethod is buggy in powershell < 6 Version, so if youre will with the standard V5 Windows Version, check the response headers via invoke-webservice, and if the response header is:
"application/json"
and not
"application/json; charset=utf-8"
powershell will misinterpret this as a windows encoding. So if youree experiencing encoding issues, you have four options:
1.) if you can modify the webservice, change the response header
2.) switch to a newer powershell version (v7 is recommended)
3.) build your own webservice call directly via the .net cmdlets
4.) use the invoke-webservice, write the answer directly into a file with the OutFile Paramater
see also:
Powershell Invoke-RestMethod incorrect character
There might be some methods to get access to RESTful APIs from my research.
Httpclient? using id and password might be not secure.
What is the way to get access to Azure Devops with a personal token?
any example code?
the code below is what I have tried and it showed credential failed.
thank you.
powershell code
function InputToPowerBI {
param ([string]$type,[string]$title,[string]$assignedTo,[string]$state)
$endpoint = "address of the end point"
$payload = #{
"Type" =$type
"Title" =$title
"Assigned To" =$assignedTo
"State" =$state
"Area Path" =$areaPath
"Tags" =$tag
"Comment Count" =$commentCount
}
$json = ConvertTo-Json #($payload);
Invoke-RestMethod -Method Post -Uri "$endpoint" -Body $json
}
GetData;
function GetData
{
try
{
$personalAccessToken="Personal token such as eiejr22837482";
$token = [System.Convert]::ToBase64String([System.Text.Encoding]::ASCII.GetBytes(":$($personalToken)"))
$header = #{authorization = "Basic $token"}
$projectsUrl = "address of the current sprint from Azure DevOps"
$projects = Invoke-RestMethod -Uri $projectsUrl -Method Get -ContentType "application/json" -Headers $header
$projects.value | ForEach-Object {
}
}
catch
{
}
}