2

Silly question, but cant seem to figure it out. How do I expand the content of a variable, and show the result in single quotes ?

    $Test = Hello
    Write-output $($Test)

I would like the result to be 'Hello' including the quotes.

BenDK
  • 131
  • 2
  • 7
  • `Write-Output "'$($Test)'"` should yield the result you're after (note the double quotes to create a String and then the single quotes within that String). Also you need to enclose "Hello" in quotes `$Test = "Hello"` so that PowerShell interprets it as a String. – Jacob Nov 10 '18 at 17:37
  • Thanks for quick reply :) – BenDK Nov 10 '18 at 17:40
  • if you ALWAYS want the quotes to be there, you can save them as part of the $Var value. for instance, this `"'Hello'"` will print with the internal set of quotes. not that it is `Hello` and you can reverse them if you prefer to store the doubles instead of the singles. [*grin*] – Lee_Dailey Nov 10 '18 at 17:46
  • Had to use it like this `$("'$Test'")` , but you pointed me in the right direction – BenDK Nov 10 '18 at 17:49
  • I don't always want them to be single quotes, as the message is just for generating email and a log file, I use the variable for other useful stuff in my script, but thanks anyway – BenDK Nov 10 '18 at 17:52

1 Answers1

3

With an expandable string (string interpolation):

# To embed *expressions*, additionally enclose in $(...); e.g., "'$($Test+1)'"
"'$Test'" 

As a general aside: In order to merely output a value, there's no need for Write-Output, because PowerShell implicitly outputs expression / command results (that are neither captured nor redirected).

You can pass the expression above as-is as an argument to a command, there is no need for $(...), the subexpression operator; sticking with the Write-Output sample command:

Write-Output "'$Test'"

Use expandable strings as a convenient way of embedding the default string representation of a variable value or expression result in a string.


With -f, the string-formatting operator (internally based on String.Format):

"'{0}'" -f $Test  # {0} is a placeholder for the 1st RHS operand

# Enclose in (...) to pass the expression as an argument to a command:
Write-Output ("'{0}'" -f $Test)

The -f operator gives you more control over the resulting string representation, allowing you to perform operations such as padding and selecting the number of decimal places for floating-point numbers.

Note, however that this approach is suitable only for scalars, not arrays (collections).


With string concatenation (+):

"'" + $Test + "'"

# Enclose in (...) to pass the expression as an argument to a command:
Write-Output ("'" + $Test + "'")

This a more verbose alternative to string expansion that makes the operation being performed more obvious.

mklement0
  • 382,024
  • 64
  • 607
  • 775