Home > Net >  How to add json object to arguments
How to add json object to arguments

Time:12-29

I'm trying to add json object to my powershell script using cmd. My issue, is that I receive the string but without any quotes.

My script.ps1:

Write-Host ($args[0] | Format-Table | Out-String)

My command line :

C:\path\to\powershell.exe ./script.ps1 '{"key1":"val1","all":[{"key2":"val2","key3":"val3","key4":["val5","val6"]},{"key5":"val7","key6":"val8","key7":["val9","val10"]}],"key8":0}'

Result :

{key1:val1,all:[{key2:val2,key3:val3,key4:[val5,val6]},{key5:val7,key6:val8,key7:[val9,val10]}],key8:0}

How can I get my json with quotes ?

CodePudding user response:

When using PowerShell's CLI, unescaped " on the command line are removed during command-line parsing, and only then is the result interpreted as PowerShell code to execute (due to the (implied) use of the -Command / -c parameter).[1]

You have two options:

  • As Compo notes and demonstrates in his comment, escaping all " chars. as \" would work - the escaping ensures that they are retained, in unescaped form, and therefore become part of the PowerShell code to execute.

  • If you want to avoid escaping, provide the text via the pipeline (stdin):

echo {"key1":"val1","all":[{"key2":"val2","key3":"val3","key4":["val5","val6"]},{"key5":"val7","key6":"val8","key7":["val9","val10"]}],"key8":0}| powershell.exe -c ./script.ps1 $input

Note the absence of a space before |, as such spaces would otherwise become part of the input.

In the PowerShell command, the piped-in text is accessed via the automatic $input variable


[1] It is for this reason that the outer '...' quoting does not protect the unescaped " inside it: During the initial parsing of the command line, ' characters have no syntactic meaning.

  • Related