live2learn
live2learn

Reputation: 911

How to create a raw body for POST request using PowerShell

I am trying a POST request using PowerShell. It takes body of type raw. I know how to pass form-data using PowerShell, however not sure for rawdata type. For a simple raw-data in Postman e.g.

{
"@type":"login",
 "username":"[email protected]",
 "password":"yyy"
}

I pass below in PowerShell and it works fine.

$rawcreds = @{
               '@type' = 'login'
                username=$Username
                password=$Password
             }

        $json = $rawcreds | ConvertTo-Json

However, for a complex rawdata like below, I am unsure how to pass in PowerShell.

{
    "@type": Sample_name_01",
    "agentId": "00000Y08000000000004",
    "parameters": [
        {
            "@type": "TaskParameter",
            "name": "$source$",
            "type": "EXTENDED_SOURCE"
        },
        {
            "@type": "TaskParameter",
            "name": "$target$",
            "type": "TARGET",
            "targetConnectionId": "00000Y0B000000000020",
            "targetObject": "sample_object"
        }
    ],
    "mappingId": "00000Y1700000000000A"
}

Upvotes: 4

Views: 12271

Answers (1)

briantist
briantist

Reputation: 47862

My interpretation is that your second code block is the raw JSON you want, and you're not sure how to construct that. The easiest way would be to use a here string:

$body = @"
{
    "@type": Sample_name_01",
    "agentId": "00000Y08000000000004",
    "parameters": [
        {
            "@type": "TaskParameter",
            "name": "$source$",
            "type": "EXTENDED_SOURCE"
        },
        {
            "@type": "TaskParameter",
            "name": "$target$",
            "type": "TARGET",
            "targetConnectionId": "00000Y0B000000000020",
            "targetObject": "sample_object"
        }
    ],
    "mappingId": "00000Y1700000000000A"
}
"@

Invoke-WebRequest -Body $body

Variable substitution works (because we used @" instead of @') but you don't have to do messy escaping of literal " characters.

So what that means is that $source$ will be interpreted as a variable named $source to be embedded in the string followed by a literal $. If that's not what you want (that is, if you want to literally use $source$ in the body), then use @' and '@ to enclose your here string so that powershell variables are not embedded.

Upvotes: 8

Related Questions