RestMethod无论做什么都返回400错误

分享于 

3分钟阅读

互联网

  繁體

问题:

代码如下:


 import-module dbatools



# Import API Config from user's profile


$config = Get-Content ~.samanagecreds.json | ConvertFrom-Json



#Dictionary of headers


$headers = @{


 'Accept' = 'application/vnd.samanage.v2.1+json'


 'Content-Type' = 'application/json'


 'X-Samanage-Authorization'= "Bearer $($config.api_key)"


}



#Now how do we find incidences assigned to this user?


$all_alfreds_tickets = Invoke-RestMethod -Method "GET" -URI "https://api.samanage.com/incidents.json?assigned_to=6671937" -Headers $headers



# loop through all the tickets that came back from our API Call


$all_alfreds_tickets| foreach-object -process {



 $ticket = $_



 # Do thing based on ticket category


 switch ($_.subcategory[0].name){



 # How does Alfred handle a Workstation exception request?


 ('Alfred-Workstation Exceptions'){



 #


 # Check Ticket status, if state != Request work the ticket


 #



 # Move the computer into the workstation exceptions out 


 Get-ADComputer $ticket.name | Move-ADObject -TargetPath <Path to OU>



 # Respond to the tick letting the world know what's been done.


 Invoke-RestMethod -Method POST -URI "https://api.samanage.com/incidents/$($ticket.id)/comments.json" -headers $headers -Body '{"body": "Hello, I have moved this computer to the Workstation Exceptions OU", "State": "In-Progress",}'



 # Update the ticket status to "In-Progress"


 Invoke-RestMethod -Method Put -URI "https://api.samanage.com/incidents/$($ticket.id).json -headers $headers -body '{"state":"In-Progress"}'## Heading ##



 # Add the ticket to the database for monitoring.



 }


 }


}



我的麻烦是无论我做什么我都无法使Invoke-RestMethod成功工作。

我尝试了几种不同的方法:

Put : Invoke-RestMethod returns "400, Bad Request"

Post : Invoke-RestMethod returns " 404, not Found"

Patch : Invoke-RestMethod returns "403, forbidden"


答案1:

必须作为JSON对象发送。


答案2:


$url = "https://api.samanage.com/incidents/$($ticket.id)/comments.json"


$body = @{


 "body" = "Hello, I have moved this computer to the Workstation Exceptions OU"


 "State" = "In-Progress"


} | ConvertTo-Json



Invoke-RestMethod -Method POST -URI $url -headers $headers -Body $body -ContentType "application/json"





REST  MAT  returns