Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Powershell - add variables inside a json string

Tags:

powershell

I have the following json code in my powershell script. I set the $variable to 1111111111

$jsonfile = '{"Version": "2012-10-17","Statement": {"Effect": "Allow","Action": "sts:AssumeRole","Resource": "arn:aws:iam::$variable:role/xxxxxx"}}'

The output gives ....arn:aws:iam::$variable:role/xxxxxx..... instead of ....arn:aws:iam::1111111111:role/xxxxxx

The problem is that I must use the single quote for the json string otherwise I will get an error. If I use single quote I wont be able to put the variables inside the string. How do I workaround this problem?

like image 659
tset Avatar asked Jul 15 '16 03:07

tset


People also ask

Can you put variables in JSON?

Variables provide a new way to tackle different scenarios where JSON schema alone fails. This means, that you can use a new keyword named $vars to make your life easier.

How do I add a variable to a string in PowerShell?

PowerShell has another option that is easier. You can specify your variables directly in the strings. $message = "Hello, $first $last." The type of quotes you use around the string makes a difference.

How do I combine strings and variables in PowerShell?

In PowerShell, string concatenation is primarily achieved by using the “+” operator. There are also other ways like enclosing the strings inside double quotes, using a join operator, or using the -f operator.

Can you use variables in PowerShell?

In PowerShell, variables are represented by text strings that begin with a dollar sign ( $ ), such as $a , $process , or $my_var . Variable names aren't case-sensitive, and can include spaces and special characters.


1 Answers

There are various ways to solve your problem, but perhaps the easiest approach is to use PowerShell's string interpolation:

  • use a double-quoted string overall to enable interpolation of embedded variable references and subexpressions ($(...)).

  • escape embedded " chars. as `" (using backticks)

  • disambiguate variable references by enclosing the variable name in {...}.

Simplified example:

PS> $variable='111'
PS> "{`"Version`": `"arn:aws:iam::${variable}:role/xxxxxx`"}}"
{"Version": "arn:aws:iam::111:role/xxxxxx"}}

Note that enclosing variable names in {...} in interpolated strings is only necessary if the following char. could be misinterpreted as part of the variable name.
A : following the variable name - as is the case here - is such a case, because PS variables can have a scope specifier preceding the variable name that is separated from the variable name with :, such as in $env:USERNAME.


DAXaholic's helpful answer shows an alternative based on PowerShell's binary -f operator, which is essentially the same as the .NET framework's String.Format method; as such:

  • it introduces additional complexity, such as needing to know what its escaping rules are ({ chars. must be escape as {{, and how to format its arguments specified on the RHS of -r ({0} refers to the 1st RHS argument, ...)

  • on the flip side, -f offers many sophisticated formatting options.

Also, consider use of the Convert*-Json cmdlets his answer demonstrates: even though they're less performant, they ultimately make manipulation of JSON much easier and more robust.


Alternatives in the realm of native PowerShell code:

  • String concatenation with the binary + operator:
'{"Version": "arn:aws:iam::' + $variable + ':role/xxxxxx"}}'
  • String templating with $ExecutionContext.InvokeCommand.ExpandString():
$variable='111'    
$tmpl = '{"Version": "arn:aws:iam::${variable}:role/xxxxxx"}}' # string template *literal*
$ExecutionContext.InvokeCommand.ExpandString($tmpl) # performs on-demand interpolation
like image 130
mklement0 Avatar answered Sep 18 '22 17:09

mklement0