Happy.Hartman
Happy.Hartman

Reputation: 293

PowerShell - Pass a variable within a variable that has quotes for JSON

I'm working on an API to create a tenant in QRadar. I have this basic script that I'm using and I've ran into essentially the same problem before but now it got a little more complex.

Here is the code I'm using:

$QRadarIP = 'xxx.xxx.xxx.xxx'
$authtoken = 'blahblahblah'
$SECHeader = @(
"SEC: $authtoken"
)

$name = 'test4'
$description = 'The fourth test'

$TenantInput = @('{"deleted": false,"description": $description,"event_rate_limit": 0,"flow_rate_limit": 0,"name": $name}')

curl.exe -S -X POST -k -H $SECHeader -H 'Content-Type: application/json' -H 'Version: 15.1' -H 'Accept: application/json' --data-binary $TenantInput $tenantURI

So the problem I'm running into is that $name and $description are getting passed as literals instead of the value from the variable. The string within the $TenantInput is JSON and those quotes are apparently necessary for the way that the JSON is interpreted. I'm trying to put that variable in the @() because that's what I used to fix my issue of passing the auth token into the SEC header and then into the curl command.

I've looked at other questions on here that were similar but there's always something about the scenario that is different than mine to where I can't decipher it. Any advice is appreciated.

Upvotes: 1

Views: 569

Answers (2)

Happy.Hartman
Happy.Hartman

Reputation: 293

So @Damien was right, the final-ish solution came down to me adding those backticks and quotes in front of the variable but also replacing my spaces with underscores soo like below:

$name6 = "test5"
$description6 = "The_fifth_test"
$TenantInput = @("{`"deleted`": false,`"description`": `"${description6}`",`"event_rate_limit`": 0,`"flow_rate_limit`": 0,`"name`": `"${name6}`"}")

it's definitely a bummer that I have to use the underscores in the string so I'm sure there's still a better answer than what I eventually stopped with.

Upvotes: 0

Damien
Damien

Reputation: 156

The solution is:

$TenantInput = @("{`"deleted`": false,`"description`": ${description},`"event_rate_limit`": 0,`"flow_rate_limit`": 0,`"name`": ${name}}")

You need to use double quotes and define variables in ${}

To understand the quotes in String you can read this blog (with examples): https://www.computerperformance.co.uk/powershell/quotes/

Upvotes: 2

Related Questions