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.
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.
Or make an object then convert it to compressed json:
$userid,$timestamp,$numberout,$numberout,$numberout = echo 261 AAAAAAAJ1KM 5503 5503 5503
[pscustomobject]#{Id=$userid;Timestamp=$timestamp;FirstName=$numberout;
LastName=$numberout;CallId=$numberout} | convertto-json -compress
{"Id":261,"Timestamp":"AAAAAAAJ1KM=","FirstName":"5503","LastName":"5503","CallId":"5503"}
Related
I have a string that I want to insert dynamically a variable. Ex;
$tag = '{"number" = "5", "application" = "test","color" = "blue", "class" = "Java"}'
I want to accomplish:
$mynumber= 2
$tag = '{"number" = "$($mynumber)", "application" = "test","color" = "blue", "class" = "Java"}'
What I want is to have the variable inserted on the string, But it is not going through. I guess the '' sets all as a string. Any recomendations on how should I approach this?
thanks!
powershell test and trial and error. Also Google.
The reason your current attempt doesn't work is that single-quoted (') string literals in PowerShell are verbatim strings - no attempt will be made at expanding subexpression pipelines or variable expressions.
If you want an expandable string literal without having to escape all the double-quotes (") contained in the string itself, use a here-string:
$mynumber = 2
$tag = #"
{"number" = "$($mynumber)", "application" = "test","color" = "blue", "class" = "Java"}
"#
To add to Mathias' helpful answer:
Mistakenly expecting string interpolation inside '...' strings (as opposed to inside "...") has come up many times before, and questions such as yours are often closed as a duplicate of this post.
However, your question is worth answering separately, because:
Your use case introduces a follow-up problem, namely that embedded " characters cannot be used as-is inside "...".
More generally, the linked post is in the context of argument-passing, where additional rules apply.
Note: Some links below are to the relevant sections of the conceptual about_Quoting_Rules help topic.
In PowerShell:
only "..." strings (double-quoted, called expandable strings) perform string interpolation, i.e. expansion of variable values (e.g. "... $var" and subexpressions (e.g., "... $($var.Prop)")
not '...' strings (single-quoted, called verbatim strings), whose values are used verbatim (literally).
With "...", if the string value itself contains " chars.:
either escape them as `" or ""
E.g., with `"; note that while use of $(...), the subexpression operator never hurts (e.g. $($mynumber)), it isn't necessary with stand-alone variable references such as $mynumber:
$mynumber= 2
$tag = "{`"number`" = `"$mynumber`", `"application`" = `"test`",`"color`" = `"blue`", `"class`" = `"Java`"}"
Similarly, if you want to selectively suppress string interpolation, escape $ as `$
# Note the ` before the first $mynumber.
# -> '$mynumber = 2'
$mynumber = 2; "`$mynumber` = $mynumber"
See the conceptual about_Special_Characters help topic for info on escaping and escape sequences.
If you need to embed ' inside '...', use '', or use a (single-quoted) here-string (see next).
or use a double-quoted here-string instead (#"<newline>...<newline>"#):
See Mathias' answer, but generally note the strict, multiline syntax of here-strings:
Nothing (except whitespace) must follow the opening delimiter on the same line (#" / #')
The closing delimiter ("# / '#) must be at the very start of the line - not even whitespace may come before it.
Related answers:
Overview of PowerShell's expandable strings
Overview of all forms of string literals in PowerShell
When passing strings as command arguments, they are situationally implicitly treated like expandable strings (i.e. as if they were "..."-enclosed); e.g.
Write-Output $HOME\projects - see this answer.
Alternatives to string interpolation:
Situationally, other approaches to constructing a string dynamically can be useful:
Use a (verbatim) template string with placeholders, with -f, the format operator:
$mynumber= 2
# {0} is the placeholder for the first RHS operand ({1} for the 2nd, ...)
'"number" = "{0}", ...' -f $mynumber # -> "number" = "2", ...
Use simple string concatenation with the + operator:
$mynumber= 2
'"number" = "' + $mynumber + '", ...' # -> "number" = "2", ...
I have a string that I want to insert dynamically a variable. Ex;
$tag = '{"number" = "5", "application" = "test","color" = "blue", "class" = "Java"}'
I want to accomplish:
$mynumber= 2
$tag = '{"number" = "$($mynumber)", "application" = "test","color" = "blue", "class" = "Java"}'
What I want is to have the variable inserted on the string, But it is not going through. I guess the '' sets all as a string. Any recomendations on how should I approach this?
thanks!
powershell test and trial and error. Also Google.
The reason your current attempt doesn't work is that single-quoted (') string literals in PowerShell are verbatim strings - no attempt will be made at expanding subexpression pipelines or variable expressions.
If you want an expandable string literal without having to escape all the double-quotes (") contained in the string itself, use a here-string:
$mynumber = 2
$tag = #"
{"number" = "$($mynumber)", "application" = "test","color" = "blue", "class" = "Java"}
"#
To add to Mathias' helpful answer:
Mistakenly expecting string interpolation inside '...' strings (as opposed to inside "...") has come up many times before, and questions such as yours are often closed as a duplicate of this post.
However, your question is worth answering separately, because:
Your use case introduces a follow-up problem, namely that embedded " characters cannot be used as-is inside "...".
More generally, the linked post is in the context of argument-passing, where additional rules apply.
Note: Some links below are to the relevant sections of the conceptual about_Quoting_Rules help topic.
In PowerShell:
only "..." strings (double-quoted, called expandable strings) perform string interpolation, i.e. expansion of variable values (e.g. "... $var" and subexpressions (e.g., "... $($var.Prop)")
not '...' strings (single-quoted, called verbatim strings), whose values are used verbatim (literally).
With "...", if the string value itself contains " chars.:
either escape them as `" or ""
E.g., with `"; note that while use of $(...), the subexpression operator never hurts (e.g. $($mynumber)), it isn't necessary with stand-alone variable references such as $mynumber:
$mynumber= 2
$tag = "{`"number`" = `"$mynumber`", `"application`" = `"test`",`"color`" = `"blue`", `"class`" = `"Java`"}"
Similarly, if you want to selectively suppress string interpolation, escape $ as `$
# Note the ` before the first $mynumber.
# -> '$mynumber = 2'
$mynumber = 2; "`$mynumber` = $mynumber"
See the conceptual about_Special_Characters help topic for info on escaping and escape sequences.
If you need to embed ' inside '...', use '', or use a (single-quoted) here-string (see next).
or use a double-quoted here-string instead (#"<newline>...<newline>"#):
See Mathias' answer, but generally note the strict, multiline syntax of here-strings:
Nothing (except whitespace) must follow the opening delimiter on the same line (#" / #')
The closing delimiter ("# / '#) must be at the very start of the line - not even whitespace may come before it.
Related answers:
Overview of PowerShell's expandable strings
Overview of all forms of string literals in PowerShell
When passing strings as command arguments, they are situationally implicitly treated like expandable strings (i.e. as if they were "..."-enclosed); e.g.
Write-Output $HOME\projects - see this answer.
Alternatives to string interpolation:
Situationally, other approaches to constructing a string dynamically can be useful:
Use a (verbatim) template string with placeholders, with -f, the format operator:
$mynumber= 2
# {0} is the placeholder for the first RHS operand ({1} for the 2nd, ...)
'"number" = "{0}", ...' -f $mynumber # -> "number" = "2", ...
Use simple string concatenation with the + operator:
$mynumber= 2
'"number" = "' + $mynumber + '", ...' # -> "number" = "2", ...
I have a string like this in below and I want replace space with backslash and space.
let test: String = "Hello world".replacingOccurrences(of: " ", with: "\ ")
print(test)
But Xcode make error of :
Invalid escape sequence in literal
The code in up is working for any other character or words, but does not for backslash. Why?
Backslash is used to escape characters. So to print a backslash itself, you need to escape it. Use \\.
For Swift 5 or later you can avoid needing to escape backslashes using the enhanced string delimiters:
let backSlashSpace = #"\ "#
If you need String interpolation as well:
let value = 5
let backSlashSpaceWithValue = #"\\#(value) "#
print(backSlashSpaceWithValue) // \5
You can use as many pound signs as you wish. Just make sure to mach the same amount in you string interpolation:
let value = 5
let backSlashSpaceWithValue = ###"\\###(value) "###
print(backSlashSpaceWithValue) // \5
Note: If you would like more info about this already implemented Swift evolution proposal SE-0200 Enhancing String Literals Delimiters to Support Raw Text
Due to the document of glib.string.escape()
Escapes the special characters '\b', '\f', '\n', '\r', '\t', '\v', '\' and '"' in the string source by inserting a '\' before them.
Additionally all characters in the range 0x01-0x1F (everything below SPACE) and in the range 0x7F-0xFF (all non-ASCII chars) are replaced with a '\' followed by their octal representation. Characters supplied in exceptions are not escaped.
Now I want not eacape "0x7F-0xFF" characters. How to write the exceptions part?
my example code no work.
shellcmd = "bash -c \""+file.get_string(title,"List").escape("0x7F-0xFF")+"\"";
print("shellcmd: %s\n", shellcmd);
Process.spawn_command_line_sync (shellcmd,
out ls_stdout, out ls_stderr, out ls_status);
if(ls_status!=0){ list = ls_stderr.split("\n"); }
else{ list = ls_stdout.split("\n"); }
this works.
shellcmd = "bash -c \""+file.get_string(title,"Check").replace("\"","\\\"")+"\"";
You actually have to put the characters 0x7f to 0xff in the exceptions argument. So something like:
shellcmd = "bash -c \""+file.get_string(title,"List").escape("\x7F\x80\x81\x82…\xfe\xff")+"\"";
You would need to list them all manually.
Looking more generally at your code, you seem to be constructing a command to run. This is a very bad idea and you should never do it. It is wide open to code injection. Use Process.spawn_sync() and pass it an argument vector instead.
I want to run the following PowerShell script file from Jenkins Pipeline:
".\Folder With Spaces\script.ps1"
I have been able to do it with the following step definition:
powershell(script: '.\\Folder` With` Spaces\\script.ps1')
So I have to remember to:
escape the backslash with a double backslash (Groovy syntax)
escape the space with backtick (PowerShell syntax)
I would prefer to avoid at least some of this. Is it possible to avoid using the backtick escaping, for example? (Putting it between "" does not seem to work, for some reason.)
I found that it's possible to use the ampersand, or invoke, operator, like this:
powershell(script: "& '.\\Folder With Spaces\\script.ps1'")
That gets rid of the backtick escaping, and should make life a tiny bit easier.
To avoid escaping the backslashes you could use slashy strings or dollar slashy strings as follows. However you cannot use a backslash as the very last character in slashy strings as it would escape the /. Of course slashes as well would have to be escaped when using slashy strings.
String slashy = /String with \ /
echo slashy
assert slashy == 'String with \\ '
// won't work
// String slashy = /String with \/
String dollarSlashy = $/String with / and \/$
echo dollarSlashy
assert dollarSlashy == 'String with / and \\'
And of course you'll lose the possibility to include newlines \n and other special characters in the string using the \. However as both slashy and dollar slashy strings have multi line support at least newlines can be included like:
String slashyWithNewline = /String with \/ and \
with newline/
echo slashyWithNewline
assert slashyWithNewline == 'String with / and \\ \nwith newline'
String dollarSlashyWithNewline = $/String with / and \
with newline/$
echo dollarSlashyWithNewline
assert dollarSlashyWithNewline == 'String with / and \\ \nwith newline'
If you combine that with your very own answer you won't need both of the escaping.