I have managed to connect to the Graph API and I'm able to pull data without any issues. I now want to add a user to a group and I cannot for the life of me get it to work. The MS documentation says its POST https://graph.microsoft.com/v1.0/groups/{id}/members/$ref. I believe $ref is the reference to the user in the format below. How, in Powershell, do I submit this using Invoke-RestMethod?
{
"#odata.id": "https://graph.microsoft.com/v1.0/users/a0fbxxxb7-2b3d-4df1-a0ce-3bfdb513dxxx"
}
According to my reserach, please try to update your body as
{
"#odata.id": "https://graph.microsoft.com/v1.0/directoryObjects/a0fbxxxb7-2b3d-4df1-a0ce-3bfdb513dxxx"
}
For example
$headers = New-Object "System.Collections.Generic.Dictionary[[String],[String]]"
$headers.Add("Content-Type", "application/json")
$headers.Add("Authorization", "Bearer <access_token>")
$body = "{`"#odata.id`": `"https://graph.microsoft.com/v1.0/directoryObjects/<the user objectid>`"}"
$response = Invoke-RestMethod 'https://graph.microsoft.com/v1.0/groups/022af724-22e4-4838-92e9-4e561f9acc0c/members/$ref' -Method 'POST' -Headers $headers -Body $body
Related
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.
I am new to using Azure APIs to create an automation script to do the merge of ReleaseCandidate to master post production release.
For that I am trying to create a pull request using the Azure REST APIs. but facing the below error:
Invoke-WebRequest : {"$id":"1","innerException":null,"message":"Invalid argument value.\r\nParameter name: Both a source and target reference is required.
My request body is like below:
$requestBody = #{
targetRefName = "refs/heads/master";
sourceRefName = "refs/heads/release/Release-2.42.0";
reviewers = "77c0ffe29d3169a58ca0737bc05b76f9";
title = "post release merge to master"
}
Request:
$AzurePRUrl = "https://dev.azure.com/{organisation}/_apis/git/repositories/{$RepositoryId}/pullrequests?api-version=5.0"
$AzureCreatePRResult = $(Invoke-WebRequest -Uri $AzurePRUrl -UseBasicParsing -ContentType 'application/json' -Headers $Headers -Method post -Body $requestBody | ConvertTo-Json).content
No information on documentation or anywhere else related to this type of error. I am stuck at the moment. Please suggest.
According to my test, the reviewers should a list of objects. For more details, please refer to the document. So please update $requestBody as #{ targetRefName = "refs/heads/master"; sourceRefName = "refs/heads/release/Release-2.42.0"; reviewers =#{ "id"="77c0ffe29d3169a58ca0737bc05b76f9"}; title = "post release merge to master" }.
For example
$requestBody = #{
targetRefName = "refs/heads/master";
sourceRefName = "refs/heads/test1";
reviewers = #{"id"="d33731c1-c059-6d48-9408-be0e725276f4"};
title = "post powershell script to test"
} | ConvertTo-Json
$AzurePRUrl = "https://dev.azure.com/{organisation}/_apis/git/repositories/{$RepositoryId}/pullrequests?api-version=5.1"
$result=(Invoke-WebRequest -UseBasicParsing -Uri $url -Headers $headers -ContentType "application/json" -Method Post -Body $requestBody)
$result.Content
I am trying to connect to Azure Machine Learning Web service using Invoke-WebRequest in PowerShell. after bellow command I will get an error that "Request is unauthorized to access
resource.":
Invoke-WebRequest -Uri $Url -Method POST -Body $body
As I know, you can connect to a Machine Learning Web service using any programming language that supports HTTP request and response. read more about it here.
Seems I need to pass API Key with my request. I have tried this two types of command, but the error was same:
Invoke-WebRequest -Uri $Url -Method POST -Body $body -Headers #{'apikey' = $API_key}
and
Invoke-WebRequest -Uri $Url -Method POST -Body $body -Header #{ "X-ApiKey" = $API_key }
Can you please guide me how I can pass API Key to the Azure Machine Learning Web service using PowerShell?
Per TheIncorrigible's comment, try this:
Invoke-WebRequest -Uri $Url -Method POST -Body $body -Headers #{ Authorization = "Bearer " + $API_key }
You are passing a JSON string, so you could also just use the ConvertTo-Json command to create your true API key. For info on that check this out: using powershell with JSON data
You should use this:
Invoke-WebRequest -Uri $Url -Method POST -Body $body -Headers #{ 'Content-Type' = 'application/json'; 'Authorization' = "Bearer " + $API_key }
At this microsoft documentation address
https://learn.microsoft.com/en-us/azure/templates/microsoft.sql/servers/databases
I found the following note in many parameters:
To see possible values, query the capabilities API.
Unfortunately it's not explained how to query "the capabilities API"
Any idea?
Check this official document.
GET https://management.azure.com/subscriptions/{subscriptionId}/providers/Microsoft.Sql/locations/{locationId}/capabilities?api-version=2014-04-01
You could call the api with Power Shell(just an example, you also could use other language to call the API).
##get token
$TENANTID=""
$APPID=""
$PASSWORD=""
$result=Invoke-RestMethod -Uri https://login.microsoftonline.com/$TENANTID/oauth2/token?api-version=1.0 -Method Post -Body #{"grant_type" = "client_credentials"; "resource" = "https://management.core.windows.net/"; "client_id" = "$APPID"; "client_secret" = "$PASSWORD" }
$token=$result.access_token
##set subscriptionId
$subscriptionId=""
$Headers=#{
'authorization'="Bearer $token"
'host'="management.azure.com"
'contentype'='application/json'
}
$url="https://management.azure.com/subscriptions/$subscriptionId/providers/Microsoft.Sql/locations/eastus/capabilities?api-version=2014-04-01"
Invoke-RestMethod -Uri $url -Headers $Headers -Method GET
I'm trying to create an event in a calendar in an Office 365 group via powershell.
This is my first experience to do this type of programming so sorry if my question will be very basic :-)
First, I created a simple json file (calendar.json)
{
"start":
{
"dateTime":"2017-03-12T17:00:00.0000000",
"timeZone":"UTC"
},
"end":
{
"dateTime":"2017-03-12T17:30:00.0000000",
"timeZone":"UTC"
},
"responseStatus": {
"response": "None"
},
"iCalUId": "null",
"isReminderOn": false,
"subject": "Test Event created from API"
}
Then I create the event with these steps:
Use a tested powershell function that give me the token
Add header with this code:
$headers = #{}
$headers.Add('Authorization','Bearer ' + $token.AccessToken)
$headers.Add('Content-Type',"application/json")
Because I'm starting now, I convert the json file in an object and then the object in json (I know, it's quite stupid, but I've done so beacuse I have no knowledge of json and how convert without error in powershell code)
$json = ConvertFrom-Json -InputObject (Gc 'C:\Users\mmangiante\OneDrive - Interactive Media S.p.A\Office 365\calendar.json'-Raw)
$body = ConvertTo-Json $json
Call the Invoke-RestMethod
response = Invoke-RestMethod 'https://graph.microsoft.com/v1.0/groups/768afb0c-bafd-4272-b855-6b317a3a9953/calendar/events' -Method Post -Headers $headers -Body $json
What is returned is a 400 bad request.
It's the same error of Sending Microsoft Graph request events returns 400
Given the answer given to that question I modified my code to return the error:
try{$restp=Invoke-RestMethod 'https://graph.microsoft.com/v1.0/groups/768afb0c-bafd-4272-b855-6b317a3a9953/calendar/events' -Method Post -Headers $headers -Body $json
} catch {$err=$_}
$err
like suggested in How do I get the body of a web request that returned 400 Bad Request from Invoke-RestMethod but I found nothing of interest.
The only thing that I found is that, at the time of writing, the Invoke-RestMethod doesn't return the full response as in this https://github.com/PowerShell/PowerShell/issues/2193
I suppose my json is not "well formed", but I don't know why.
Does anyone have a suggestion?
This formatting has worked for me in the past. Let me know if this resolves your issues:
$headers = #{
"Authorization" = ("Bearer {0}" -f $token);
"Content-Type" = "application/json";
}
$body = #{
Name1 = 'Value1';
Name2 = 'Value2';
}
$bodyJSON = $body | ConvertTo-Json
Invoke-RestMethod -Method Post -Uri <API HERE> -Headers $headers -Body $bodyJSON -OutFile $output
Thanks Shawn,
I tried your suggestion but without luck; I have done other test with 2 other api and found discordant results.
The first test is to use the graph api related to contact, creating a contact as in https://graph.microsoft.io/en-us/docs/api-reference/v1.0/api/user_post_contacts
I created the powershell representation of the sample json:
$contactbody = #{
givenName = 'Ciccio';
surname = 'Patacca';
emailAddresses = #(
#{
address = 'cicciopatacca#cicciociccio.com'
name = 'Ciccio Patacca'
}
)
businessPhones = (
'+39 555 123 4567'
)
}
and then converted in json
$contactbody = $contactbody | ConvertTo-Json
I retrieved from Azure Portal the object ID related to my user in my company and so I call the rest method:
$response = Invoke-RestMethod 'https://graph.microsoft.com/v1.0/users/e37d2dbe-bdaf-4098-9bb0-03be8c653f7d/contact' -Method Post -Headers $headers -Body $contactbody
The final result is a 400 bad request error.
So, I tried another example and reused some code retrieved from a google search.
This time I copied the powershell json representation as in the sample and converted:
$body = #{"displayName"="ps-blog"; "mailEnabled"=$false; "groupTypes"=#("Unified"); "securityEnabled"=$false; "mailNickname"="ps1" } | ConvertTo-Json
and, as stated in https://graph.microsoft.io/en-us/docs/api-reference/v1.0/api/group_post_groups I called the rest method
$response = Invoke-RestMethod 'https://graph.microsoft.com/v1.0/groups' -Method Post -Headers $headers -Body $body
and this worked.
So I thought that the previously powershell representations of the sample with the error were not correctly formed (even if when I printed it they are equal to the samples on the graph api); for test, I rewritten the last powershell of the body as this:
$body = #{
displayName = 'TestGraphGroup';
mailEnabled = $true;
groupTypes = #('Unified')
securityEnabled = $false;
mailNickname = 'TestGraphGroup'
}
$body = $body | ConvertTo-Json
and invoked last method: it worked again.
So, where I'm doing wrong?
A new SDK was released that makes this easier.
Checkout instructions on how to use it here