Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass json object as a parameter to another powershell script

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!!

like image 826
Saurabh Avatar asked Sep 01 '25 17:09

Saurabh


1 Answers

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
like image 168
Matt Avatar answered Sep 04 '25 10:09

Matt