[英]How to pass json object as a parameter to another powershell script
I am quite new to powershell stuff. 我对PowerShell的东西很陌生。 So need some help here.
因此,在这里需要一些帮助。
I want to pass a json object as a parameter to another ps1. 我想将json对象作为参数传递给另一个ps1。 From what I read after searching is that I need to convert it to powershell object from json string.
从搜索后读取的内容来看,我需要将其从json字符串转换为powershell对象。 Please correct me if I am wrong.
如果我错了,请纠正我。 This is what I am doing
这就是我在做什么
Calling script: 调用脚本:
$jsonParams = "{
`"TaskName`": `"$taskName`",
`"ExitCode`": `"$exitCode`",
`"ErrorMessage`": `"$errorMessage`"
}
$jsonObject = $jsonParams | ConvertFrom-Json
$argumentList = @($param1, $param2, $jsonObject)
Invoke-Expression "& `"$scriptPath`" $argumentList"
and in called script - 在所谓的脚本中-
param (
[string]$param1,
[string]$param2,
[Microsoft.PowerShell.Commands.JsonObject]$jsonObject
)
But, the calling script throws error 但是,调用脚本会引发错误
ConvertFrom-Json : Invalid object passed in, ':' or '}' expected. (21): {
What's wrong with this code. 此代码有什么问题。 Also, after json object is passed to called script, how should I access its values in it.
另外,在将json对象传递给被调用的脚本之后,我应该如何访问其中的值。
Thanks!! 谢谢!!
Your JSON is malformed. 您的JSON格式错误。 I think the core issue is that you have a trailing comma at the end of your JSON.
我认为核心问题是JSON末尾带有逗号。 You also don't close the opening quotation in your declaration.
您也不会在声明中关闭开头的报价。
You might have a much easier time if you use a here-string for this anyway. 如果仍然使用here-string,则可能会更轻松。 This was you don't have to use all those backticks.
这是您不必使用所有这些反引号。
$jsonParams = @"
{
"TaskName": "$taskName",
"ExitCode": "$exitCode",
"ErrorMessage": "$errorMessage"
}
"@
$jsonObject = $jsonParams | ConvertFrom-Json
$jsonObject
is already a custom object and no longer JSON. $jsonObject
已经是一个自定义对象,不再是JSON。 You don't need to do anything special with it. 您无需对其进行任何特殊处理。 Remove the type in your param block and just call the properties in your script.
删除参数块中的类型,然后在脚本中调用属性。
param (
[string]$param1,
[string]$param2,
$jsonObject
)
$jsonObject.TaskName
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.