Home > Back-end >  Invoke-ResMethod Rest API
Invoke-ResMethod Rest API

Time:05-18

This is my first time reaching out on here.

I am trying to create a script for Ivanti Appsense using json code powershell, but i hit an issue

i keep getting a return message "te request is invalid" i am hoping i can get some help so in powershell this is my code

$url = "http://server/path/api/ImmediateTask"
$cred = Get-Credential
 
$body = @"
{
   "id":"the ID",
   "operations" = [
      {
         "windowsSettingsGroupDisplayName": "_Active Setup",
         "operation":{
            "liveSettingsDelete":{
               "deleteRegistry": true,
               "deleteFiles": true,
               "preserveArchives": true
            }
         }
      }
"@
 
 
$request = Invoke-RestMethod  -Method post -Credential $cred -Uri $url -Body $body -ContentType "application/json" 
 
$request

however when i run it and use the correct credentials this is my output

output

CodePudding user response:

This might not be the whole answer to your problem, but one issue is you're sending invalid json to the API.

You can use PowerShell's features to generate the json string programmatically rather than do it by hand yourself. This way PowerShell will give you more meaningful error messages if your syntax is invalid, rather than waiting for the API to give you a generic "An error has occurred" message:

$data = [ordered] @{
    "id"         = "the ID"
    "operations" = @(
        [ordered] @{
            "windowsSettingsGroupDisplayName" = "_Active Setup"
            "operation"                       = [ordered] @{
                "liveSettingsDelete" =  [ordered] @{
                    "deleteRegistry"   = $true
                    "deleteFiles"      = $true
                    "preserveArchives" = $true
                }
            }
        }
    )
};

$json = ConvertTo-Json $data -Depth 99;

write-host $json
#{
#  "id": "the ID",
#  "operations": [
#    {
#      "windowsSettingsGroupDisplayName": "_Active Setup",
#      "operation": {
#        "liveSettingsDelete": {
#          "deleteRegistry": true,
#          "deleteFiles": true,
#          "preserveArchives": true
#        }
#      }
#    }
#  ]
#}

$data is basically building a nested hashtable structure, which PowerShell (and your IDE) will warn you about if you have missing brakcets, unclosed quotes, etc.

ConvertTo-Json converts this structured object into a json string.

You might still get errors from your API after doing this, but at least you'll know your json is valid.

  • Related