how to update only one field in body request? - powershell

I'm trying to update a release pipeline's description using the provide Rest API documentation.
How should I send a 'Put' request in order to update a field?
I've tried to manually modify and capture the request using sniffer, it seems that my code does exactly the same.
$theBody = ConvertTo-Json #{description='Added a description'}
$instance = "tfs:8080"
$collection = "Collection"
$project = "myProject"
$releaseID = 1234
$apiVersion = "?api-version=4.1-preview.6"
$URI = "http://"+$instance+"/"+$collection+"/"+$project+"/_apis/release/releases/"+$releaseID+$apiVersion
$res= Invoke-RestMethod -Method Put -Uri $URI -UseDefaultCredentials -Body $theBody -ContentType 'application/json'
write-output $res
I'm getting an error message:
the Id of the Release does not match the Id of the original release
resource. Make sure that you are trying to update the correct resource

The best way to do it is to get the release with the same URL but with Get method (and without body):
$release = Invoke-RestMethod -Method Get-Uri $URI -UseDefaultCredentials -ContentType 'application/json'
Then modify the description:
$release.description = "Added a description"
Convert the release to JSON:
$theBody = $release | ConvertTo-Json -Depth 10
And do the Put:
$res = Invoke-RestMethod -Method Put -Uri $URI -UseDefaultCredentials -Body $theBody -ContentType 'application/json'

Related

How to add/update user permissions on environment's security through REST API on Azure DevOps?

I need to add user permission when creating an environment through REST API with PowerShell.
I've looked at the network trace and this is the header when I tried to manually add a user permissions
Request URL:
https://dev.azure.com/{org}/_apis/securityroles/scopes/distributedtask.environmentreferencerole/roleassignments/resources/{project_id}_{env_id}
Request Method: Put
Request Body:
[{userId: "{id_of_user}", roleName: "Administrator"}]
And this is the code I tried:
# other code
...
$body = #(
#{ 'userId' = '{id_of_user}'; 'roleName': 'Administrator' }
) | ConvertTo-Json
Invoke-RestMethod -Uri $uri -Method Put -Body $body -ContentType "application/json" -Headers $header
But it is returning:
{"count":0,"value":{}}
The only missing thing is that in your body, you should provide an array instead of a single object, here is a working example:
$uri = "https://dev.azure.com/bauca/_apis/securityroles/scopes/distributedtask.environmentreferencerole/roleassignments/resources/{project_id}_{env_id}"
$id_of_user = 'YOUR_USER_ID'
$tokenbase = 'YOUR_PAT'
$header = #{
"authority"="dev.azure.com"
"Authorization"= "Basic $tokenbase"
"method"="PUT"
"path"="/{ORG}/_apis/securityroles/scopes/distributedtask.environmentreferencerole/roleassignments/resources/{project_id}_{env_id}"
"scheme"="https"
"accept"="application/json;api-version=5.0-preview.1;excludeUrls=true;enumsAsNumbers=true;msDateFormat=true;noArrayWrap=true"
"accept-encoding"="gzip, deflate, br"
"accept-language"="en-US,en;q=0.9,pt;q=0.8,nl;q=0.7"
"origin"="https://dev.azure.com"
"x-vss-reauthenticationaction"="Suppress"
} `
$body = "[{`"userId`":`"${id_of_user}`",`"roleName`":`"Administrator`"}]"
Invoke-RestMethod -UseBasicParsing -Uri $uri -Method "PUT" -Body $body -ContentType "application/json" -Headers $header
The returned results should be something like:
#{displayName=USER_NAME; id=USERID; uniqueName=USER_UNIQUENAME}
The API documentation is not clear about that, so, in this situations what I'd recommend you to do, is just use Chrome to do the requests through the UI, then inspect element and grab the network information of the request, after that 'Click with the right button' and then select 'Copy to Powershell' you'll see exactly what is the 'body' required to perform the request.

graph api assign manager

I'm trying to assign the manager to a user in AAD the documentation says
PUT /users/{id}/manager/$ref
but i'm not sure what to feed the $ref variable. I've tried UPN and the ID, but I keep getting
The remote server returned an error: (400) Bad Request.
Here is how i'm trying to put the manager info, but clearly i'm not doing it right or I can't read the documentation from here
$Header = #{
Authorization = "$($Request.token_type) $($Request.access_token)"
}
$bodyProcess = #{
id= "string aa9999a1-1111-11a2-abab-asfdas32"
}
$body = $bodyProcess | ConvertTo-Json
$Uri = "https://graph.microsoft.com/v1.0/users/4d5f6c5a-0e69-40b6-a86d-e825582add50/manager/$ref"
$UserData = Invoke-RestMethod -Uri $Uri -Headers $Header -Method PUT -ContentType "application/json" -Body $Body
Any help would be greatly appreciated.
thanks,
Here is the full script that works for me.
$Header = #{
Authorization = "$($Request.token_type) $($Request.access_token)"
}
$bodyProcess = #{
"#odata.id"= "https://graph.microsoft.com/v1.0/users/aa9999a1-1111-11a2-abab-asfdas32"
}
$body = $bodyProcess | ConvertTo-Json
$Uri = 'https://graph.microsoft.com/v1.0/users/4d5f6c5a-0e69-40b6-a86d-e825582add50/manager/$ref'
Invoke-RestMethod -Uri $Uri -Headers $Header -Method PUT -ContentType "application/json" -Body $Body

Invoke-WebRequest -Method 'POST' with -ContentType 'application/json' Fails

When using:
$body = #{
Manager = "spmigrationuser#contoso.com" #$item.PMEmail
Name = "some name"
Number = "Some number"
Practice = "Some Practice"
}
$response = Invoke-RestMethod -Method Post -Uri $Url -Body $body -ContentType 'application/json' # -Headers $Headers
Or
$response = Invoke-WebRequest -Method 'POST' -Uri $Url -Body $body -ContentType 'application/json' # -Headers $Headers
Neither ContentType 'application/json'
Nor
$Headers = #{'Content-Type' = 'application/json' }
-Headers $Headers
Works
The error is always:
"Invoke-WebRequest : {"error":{"code":"InvalidRequestContent","message":"The request content is not valid and could not be deserialized: 'Error parsing NaN value. Path '', line 1, position 1.'."}}"
The same call works in Postman
I am using PS 5.1 and I must have -ContentType 'application/json' otherwise PS works but the service fails
What can be the issue?
I agree with NickSalacious. Your issue is that you are not sending JSON.
If you are using Postman and just starting to do API in PowerShell. Postman has a "Code" Link in the top right hand corner of the request. Just below and to the right of the Send button. In there you can select PowerShell. This will give you a good basis to see how the same request could be ran in PowerShell.
Postman would turn your body into this:
$body = "{`n `"Manager`": `"spmigrationuser#contoso.com`",`n `"Name`": `"some name`",`n `"Number`": `"Some number`",`n `"Practice`": `"Some Practice`"`n}"
This is not the easiest to work with and to read. Learning and using ConvertTo-Json is going to help a lot more in the long run.
*Edit: Also look at Invoke-RestMethod and Invoke-WebRequest. They behave differently and sometimes one will be better than the other.
*Edit2: Figured I would put an example of another way to do it.
$request = #{
Uri = 'http://YourURI.Here'
Headers = #{ 'Authorization' = $token
'AnotherHeader?' = 'Sure'}
Method = 'POST'
Body = '{
"Manager": $item.PMEmail,
"Name": "some name",
"Number": "Some number",
"Practice": "Some Practice"
}'
ContentType = 'application/json'
}
$response = Invoke-RestMethod #request
The API requires that the body be a JSON string. You can do a simple conversion (using ConvertTo-Json) in your Invoke-RestMethod command and set the content type accordingly.
Invoke-RestMethod -Method POST -Uri $uri -Header $header -Body ($body | ConvertTo-Json) -ContentType 'application/json'
Sorry I bothered all of you.
I tested on another computer and it works fine.

Powershell how to get the result code from REST

I'm sending a POST request with ID/password and I need to get back a respond token, how can I get it and save it for later use in the script?
$loginUrl = "https://some-ip"
$params = #{
"username"="$username"
"password"="$password"
}
Invoke-WebRequest -Uri $loginUrl -Method POST -Body ($params|ConvertTo-Json) -ContentType "application/json"
Following your input:
$url = "https://some-ip"
$params = #{
"username" = $username
"password" = $password
} | ConvertTo-Json
$apiReturn = Invoke-RestMethod -Uri $url -Method POST -Body $params -ContentType "application/json"
$apiReturn can then be used as response.
Furthermore, you can use the SessionVariable parameter of Invoke-RestMethod.
$apiReturn = Invoke-RestMethod -Uri $url -Method POST -Body $params -ContentType "application/json" -SessionVariable sessionToken
$sessionToken.Headers.Add('Authorization', $apiReturn)
$sessionToken.Headers.Add('Content-Type', 'application/json')
In this scenario, you add the response token to 'Authorization' and forward the whole token to your subsequent API calls. Like this you only need to add $sessionToken and Content-Type for example is already provided.
Invoke-RestMethod -Method Post -Uri $url -WebSession $sessionToken
You can add more parameters to your Header in case it is required.

How do I access the value of a field returned by a Restful API

I have a very basic requirement to call a RESTful API. I am currently on a Windows 2012 R2 server using version 4 of PowerShell.
Here is my code:
$logon = #{
username = 'blah'
password='blah'
}
$body = $logon | ConvertTo-Json
$URI = 'https://URL/Logon'
Invoke-WebRequest -URI $URI -Method POST -Body $body -ContentType 'application/json' -Verbose
I get the following result:
{"LogonResult":"blahblahblah"}
How do I extract just the logon token to reuse as a variable? I've already put a variable at the beginning of the command:
$token = (Invoke-WebRequest -URI $URI -Method POST -Body $body -ContentType 'application/json' -Verbose).content
This returns the entire result, not just the token. How do I get just the token as a result?
You can get the value of the returned LogonResult property as follows:
$token = ((Invoke-WebRequest -URI $URI -Method POST -Body $body -ContentType 'application/json' -Verbose).content | ConvertFrom-JSON).LogonResult
Or you simplify this by using Invoke-RestMethod as this returns just the content and converts it to a PSObject automatically:
$token = (Invoke-RestMethod -URI $URI -Method POST -Body $body -ContentType 'application/json' -Verbose).LogonResult