I am quite new to powershell stuff. So need some help here.
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
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.
Thanks!!
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.
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With