首页 > 解决方案 > PowerShell - 在包含 JSON 引号的变量中传递变量

问题描述

我正在开发一个 API 来在 QRadar 中创建一个租户。我有这个我正在使用的基本脚本,我之前遇到过基本相同的问题,但现在它变得更复杂了。

这是我正在使用的代码:

$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

所以我遇到的问题是 $name 和 $description 作为文字而不是变量的值传递。$TenantInput 中的字符串是 JSON,这些引号显然对于解释 JSON 的方式是必需的。我试图将该变量放在 @() 中,因为这是我用来解决将身份验证令牌传递到 SEC 标头然后传递到 curl 命令的问题的方法。

我在这里查看了其他类似的问题,但总有一些与我的场景不同的地方,我无法破译它。任何建议表示赞赏。

标签: jsonpowershellapi

解决方案


解决方案是:

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

您需要使用双引号并在 ${} 中定义变量

要了解字符串中的引号,您可以阅读此博客(带有示例):https ://www.computerperformance.co.uk/powershell/quotes/


推荐阅读