Im having big troubles understanding, why my Powershell Code always returns code 400 on Invoke-RestMethod
This is my sample code
#leaving out clientid and tenantid intentionally
$MsalParams = @{
ClientId = $clientId
TenantId = $tenantId
Scopes = 'https://graph.microsoft.com/User.Read.All','https://graph.microsoft.com/Mail.Send','https://graph.microsoft.com/Mail.Send.Shared'
}
$MsalResponse = Get-MsalToken @MsalParams
$accessToken = $MsalResponse.AccessToken
$uri = "https://graph.microsoft.com/v1.0/me/sendMail"
$headers = @{
'Authorization' = "Bearer $accessToken"
'Content-Type' = 'application/json'
}
$email = @{
'message' = @{
'subject' = 'TestSubject'
'body' = @{
'contentType' = 'text'
'content' = 'This is just a simple mail body'
}
'toRecipients' = @(
@{
'emailAddress' = @{
'address' = "[email protected]"
}
}
)
}
}
$result = Invoke-RestMethod -Uri $uri -Headers $headers -Method Post -Body $email -ContentType "application/json"
i always get the following error
Invoke-RestMethod : Der Remoteserver hat einen Fehler zurückgegeben: (400) Ungültige Anforderung.
In ...... xxxxl.ps1:39 Zeichen:12
+ $result = Invoke-RestMethod -Uri $uri -Headers $headers -Method Post ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (System.Net.HttpWebRequest:HttpWebRequest) [Invoke-RestMethod], WebException
+ FullyQualifiedErrorId : WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeRestMethodCommand
i am using my user to login so its an "on behalf of" type of program. I am getting the access token without any problems, so it doesnt seem to be permission related. i also verified the json Structure, the syntax seems allright and the properties arejust klike in the microsoft documentation. i am using PSVersion 5.1.19041.3031
Does anybody know what the problem could be? Thanks Christoph
I also tried to use ConvertTo-Json -Depth 3 on the body but it didnt change anything.
If i use
Your code works okay if you used "depth 3" that will still give an error because of the nesting of the email Address. You might want to use fiddler to look at what you actually sending to the server which can help work out what's going wrong.