Search code examples
powershellescapingquoting

unexpected token in in expression or statement


I want to save a string with a skeletton and a few variables in there to use it later.

My string:

$moddeduserdata = ("{"Id":$userid,"Timestamp":"$timestamp","FirstName":"$numberout","LastName":"$numberout","CallId":"$numberout"}")

What I want is the following output:

{"Id":261,"Timestamp":"AAAAAAAJ1KM=","FirstName":"5503","LastName":"5503","CallId": "5503"}

so this results in the error: "unexpected token"

I also tried with ' ' instead of " " but then it just saves the line without putting in my variables.


Solution

  • You're trying to embed verbatim " characters in a double-quoted string ("..."), so you must escape them as `" ("" works too):

    $moddeduserdata = "{`"Id`":$userid,`"Timestamp`":`"$timestamp`",`"FirstName`":`"$numberout`",`"LastName`":`"$numberout`",`"CallId`":`"$numberout`"}"
    

    While single-quoted strings ('...') allow you to embed " chars. as-is (no need for escaping), they do not perform the string interpolation (expansion of embedded variable references) you need.

    For more information about PowerShell string literals, see the bottom section of this answer.