0

Description

I'm having some trouble with passing a JSON string correctly into a command. I believe that I have recreated the problem that I'm experiencing in the test believe. The JSON string uses double quoted strings that also contain double quotes in the string body.

The Problem:

When I invoke the Powershell script directly with the arguments, the script echos the JSON string correctly. When I invoke the PowerShell script using powershell.exe, the JSON string appears to be evaled or parsed in such as way that the double quotes are removed (thus making the JSON string invalid).

Examples:

# Contents test.ps1 file
echo $args[0]
echo $args[1]

# Back to PowerShell
> $a='bar'
> $b="{`"foo`": `"$a`"}"
> $b
{"foo": "bar"} # <-- Looks correct

When I invoke the test.ps1 file directly, the output looks as I would expect:

> .\test.ps1 foo $b
foo
{"foo": "bar"} # <-- Looks correct

However, if I go one level of indirection further and use the powershell.exe to invoke the command, I do not get the desired result:

> powershell.exe ".\test.ps1 foo $b"
foo
foo: bar # <-- Wrong... The curly brackets have been removed, as if it's been evaled.

> powershell.exe -command ".\test.ps1 foo $b"
foo
foo: bar # <-- Wrong... For the same reasons as the last example

I'm trying to determine how I can get the powershell.exe command to output the full JSON string with quotes.

0

1 Answer 1

4

When you pass powershell.exe a string, it invokes it as an expression.

powershell.exe "Get-Date"

This is why PowerShell invokes your string.

You can fix your issue like so:

$a='bar'
$b="{`"foo`": `"$a`"}"
powershell.exe -command {.\test.ps1 'foo' $args[0]} -args $b
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.