BenDK
BenDK

Reputation: 141

Expand variable and add results in single quotes

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.

Upvotes: 2

Views: 11419

Answers (1)

mklement0
mklement0

Reputation: 440576

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.

Upvotes: 4

Related Questions