OneDrive FB create Folder with Microsoft Graph API Powershell - powershell

I just want to create a folder one my OneDrive for Buiness Account through the Graph API. After many hours I got stuck with an error which I really can't comprehend. It says that the property 'Attributes' does not exist on type 'oneDrive.folder' and I should not use this property. The problem is that I don't use this property. After alot of research I think it has something to do with the pinned metadata or something like that. But in gerneral I really dont know what to do futher.
I used the Graph Explorer and another website to create this script.
The Error:
-1, Microsoft.SharePoint.Client.InvalidClientQueryException
The property 'Attributes' does not exist on type 'oneDrive.folder'.
Make sure to only use property names that are defined by the type.
And this is my code:
$clientId = "XXXXXXXXXXXXXX"
$tenantId = "XXXXXX.onmicrosoft.com"
$clientSecret = 'XXXXXXXXXXXX'
$uri = "https://login.microsoftonline.com/$tenantId/oauth2/v2.0/token"
$body = #{
client_id = $clientId
scope = "https://graph.microsoft.com/.default"
client_secret = $clientSecret
grant_type = "client_credentials"
}
$tokenRequest = Invoke-WebRequest -Method Post -Uri $uri -ContentType "application/x-www-form-urlencoded" -Body $body -UseBasicParsing
$token = ($tokenRequest.Content | ConvertFrom-Json).access_token
Write-Host $token
$uri = "https://graph.microsoft.com/v1.0/<ID XXXXXXX>/drive/root/children"
$method = 'POST'
$head= #{Authorization = "Bearer $token"}
$postPara= #{
name= "NewFolder"
folder= {}
} | ConvertTo-Json
$antwort = Invoke-RestMethod -Headers $head -Uri $uri -Method $method -Body $postPara -ContentType "application/json"
Write-Host $antwort
It really should work and I'm sitting on this sample task for over 10 Hours ._.

The issue with you code is
$postPara= #{
name= "NewFolder"
folder = {}
} | ConvertTo-Json
If you just output $postPara you will see the issue is because your missing the # in front of value in folder you will actually get the details from the underlying script populated in there. so try
$postPara= #{
name= "NewFolder"
folder = #{}
} | ConvertTo-Json
$postPara
Which should fix it.A good diag tool is also to use fiddler to look at the request being sent to server.

Related

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

DataBricks API Powershell

I'm having an issue using the databricks api 2.0
The invoke-rest method fails for the following error:
"Error 400 io.jsonwebtoken.IncorrectClaimException: Expected aud claim to be: https://management.core.windows.net/, but was:
https://management.azure.com."
I followed the instructions in the microsoft docs.
cls
$DataBrick = <DataBrickURL>
$DataBricksResourceID = <ResourceID>
$VaultName = <KeyVault>
$KeyName = <Key>
$apiEndpointUri = "https://management.azure.com"
$tenantId = <TenantID>
$applicationId = <ApplicationID>
$secret = Get-AzKeyVaultSecret -VaultName $VaultName -Name $KeyName -AsPlainText
$RequestAccessTokenUri = "https://login.microsoftonline.com/$tenantId/oauth2/token"
$body = "grant_type=client_credentials&client_id=$applicationId&client_secret=$encodedSecret&resource=2ff814a6-3304-4ab8-85cb-cd0e6f879c1d"
$Managementbody = "grant_type=client_credentials&client_id=$applicationId&client_secret=$encodedSecret&resource=$apiEndpointUri"
$contentType = 'application/x-www-form-urlencoded'
$AccessToken = Invoke-RestMethod -Method Post -Uri $RequestAccessTokenUri -Body $body -ContentType $contentType
Write-Output $AccessToken
$ManagementToken = Invoke-RestMethod -Method Post -Uri $RequestAccessTokenUri -Body $Managementbody -ContentType $contentType
Write-Output $Token
$apiuri = $DataBrick +"/api/2.0/clusters/get"
$headers = New-Object "System.Collections.Generic.Dictionary[[String],[String]]"
$headers.Add("Authorization", "Bearer " + $AccessToken.access_token)
$headers.Add("X-Databricks-Azure-SP-Management-Token", $ManagementToken.access_token)
$headers.Add("X-Databricks-Azure-Workspace-Resource-Id", $DataBricksResourceID)
Invoke-RestMethod -Uri $apiuri -Headers $headers
AS per documentation, resource parameter (your apiEndpointUri variable) should be https://management.core.windows.net/, but you have https://management.azure.com
Based on e.g. mentioned in Question, There are following steps are happening:
Get a token from Microsoft login service for provided resource id of databircks.
Get a management Token. In your e.g., it is provided as "https://management.azure.com" which is not correct. You needs to use "https://management.core.windows.net/" which is mentioned in error response too. You can refer https://learn.microsoft.com/en-us/azure/databricks/dev-tools/api/latest/aad/service-prin-aad-token#--api-access-for-service-principals-that-are-not-workspace-users for reference which is not for Powershell but useful enough to understand authentication flow
Using both tokens, to call Databricks APIs
In short, if you correct apiEndpointUri based on error. It should work provided other details are correct and have correct permission configured.

Unable to ingest JSON data into Azure Event Hub

I wrote the below Powershell script to get the JSON data from an API endpoint (https://data.melbourne.vic.gov.au/resource/vh2v-4nfs) and then write this data in JSON format to Azure Event hub. I am able to successfully get the data from the endpoint however the data is not getting ingested into Azure Event Hub.
Can anyone please let me know what's wrong with the below code:
$url = "https://data.melbourne.vic.gov.au/resource/vh2v-4nfs"
$apptoken = "k7lQcUCVFoROv7rQh9fSSXMkZ"
# Set header to accept JSON
$headers = New-Object "System.Collections.Generic.Dictionary[[String],[String]]"
$headers.Add("Accept","application/json")
$headers.Add("X-App-Token",$apptoken)
$results = Invoke-RestMethod -Uri $url -Method get -Headers $headers
$results
$method = "POST"
$URI = "https://YOURNS.servicebus.windows.net/eh-streetparking/messages"
$signature = "SharedAccessSignature sr=YOURNS.servicebus.windows.net%2feh-streetparking&sig=K6bfL1VjW9FUcL0B5xaI%3d&se=16722&skn=eh-sap-streetparking"
#$authInfo = [System.Convert]::ToBase64String([System.Text.Encoding]::UTF8.GetBytes("$signature"))
# API headers
$headers = #{
"Authorization"=$signature;
# "Content-Type"="application/json;type=entry;charset=utf-8";
"Content-Type"="application/json";
}
# execute the Azure REST API
foreach ( $result in $results)
{
Invoke-RestMethod -Uri $URI -Method $method -Headers $headers -Body $result
}
The value you have presented as the return result from your Invoke-RestMethod is actually a deserialized PowerShell object, not JSON. It appears to be having its quotes removed at some point too.
PSObject ($results) looks like this: $x = #{account_id="12345"; username="12345"; is_locked="False"; employee_id="12345"; first_name="John"; middle_initial="Roger"; last_name="Doe"; full_name="John Roger Doe"}
You can do this to access individual values:
$x.full_name
Finally, follow this syntax to send POST request:
$Cred = Get-Credential
$Url = "https://server.contoso.com:8089/services/search/jobs/export"
$Body = #{
search = "search index=_internal | reverse | table index,host,source,sourcetype,_raw"
output_mode = "csv"
earliest_time = "-2d#d"
latest_time = "-1d#d"
}
Invoke-RestMethod -Method 'Post' -Uri $url -Credential $Cred -Body $body -OutFile output.csv

PowerShell Error when queuing a build via Invoke-RestMethod and put

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:

Unlike postman, getting slow powershell script performance when used to interact with Microsoft Graph API

We are trying to use a PS script to start using Graph API:
$clientId = "XXXXXXXXXXXXXXXXXXXXXXXXXXX"
$clientSecret = "XXXXXXXXXXXXXXXXXXXXXXXXXXXX"
$TenantName = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
$resource = "https://graph.microsoft.com/"
$URL = "https://graph.microsoft.com/v1.0/groups"
$tokenBody = #{
Grant_Type = "client_credentials"
Scope = "https://graph.microsoft.com/.default"
Client_Id = $clientId
Client_Secret = $clientSecret
}
$tokenResponse = Invoke-RestMethod -Uri "https://login.microsoftonline.com/$TenantName/oauth2/v2.0/token" -Method POST -Body $tokenBody
$result = Invoke-RestMethod -Headers #{Authorization = "Bearer $($tokenResponse.access_token)"} -Uri $URL -Method Get -Verbose
($result | select-object Value).Value | Select-Object id
I am not sure if it is the script or something else but the success rate for this script is 20%. Most of the time the return is either delayed or timed out.
We are getting consistent results when we use postman to interact with the graph API. How come powershell is giving us a hard time? Is there something that we need to change on our script?
Thanks