如何将json对象作为参数传递给另一个Powershell脚本 [英] How to pass json object as a parameter to another powershell script

查看:275
本文介绍了如何将json对象作为参数传递给另一个Powershell脚本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对Powershell东西还很陌生.因此,在这里需要一些帮助.

I am quite new to powershell stuff. So need some help here.

我想将json对象作为参数传递给另一个ps1.从搜索后读取的内容来看,我需要将其从json字符串转换为powershell对象.如果我错了,请纠正我.这就是我正在做的

I want to pass a json object as a parameter to another ps1. From what I read after searching is that I need to convert it to powershell object from json string. Please correct me if I am wrong. This is what I am doing

调用脚本:

$jsonParams = "{
     `"TaskName`": `"$taskName`",
      `"ExitCode`": `"$exitCode`",
      `"ErrorMessage`": `"$errorMessage`"
   }

$jsonObject = $jsonParams | ConvertFrom-Json
$argumentList = @($param1, $param2, $jsonObject) 

Invoke-Expression "& `"$scriptPath`" $argumentList"

并在调用脚本中-

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): {

此代码有什么问题.另外,在将json对象传递给被调用的脚本之后,我应该如何访问其中的值.

What's wrong with this code. Also, after json object is passed to called script, how should I access its values in it.

谢谢!

推荐答案

您的JSON格式不正确.我认为核心问题是JSON末尾带有逗号.您也不会在声明中关闭开头的引号.

Your JSON is malformed. I think the core issue is that you have a trailing comma at the end of your JSON. You also don't close the opening quotation in your declaration.

如果您仍然使用here-string,则可能会更轻松.这是您不必使用所有反引号.

You might have a much easier time if you use a here-string for this anyway. This was you don't have to use all those backticks.

$jsonParams = @"
{
     "TaskName": "$taskName",
      "ExitCode": "$exitCode",
      "ErrorMessage": "$errorMessage"
   }
"@

$jsonObject = $jsonParams | ConvertFrom-Json


$jsonObject已经是一个自定义对象,不再是JSON.您无需对其进行任何特殊处理.删除参数块中的类型,然后在脚本中调用属性.


$jsonObject is already a custom object and no longer 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

这篇关于如何将json对象作为参数传递给另一个Powershell脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆