1

愚蠢的问题,但似乎无法弄清楚。如何扩展变量的内容,并用单引号显示结果?

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

我希望结果'Hello'包括引号。

4

1 回答 1

2

使用可扩展字符串字符串插值):

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

顺便说一句:为了仅输出一个值,不需要 for Write-Output,因为 PowerShell隐式输出表达式/命令结果(既不捕获也不重定向)。

您可以将上面的表达式按原样作为参数传递给命令,不需要$(...)表达式运算符; 坚持使用Write-Output示例命令:

Write-Output "'$Test'"

使用可扩展字符串作为将变量值或表达式结果的默认字符串表示嵌入到字符串中的便捷方式。


使用-f, 字符串格式化运算符(内部基于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)

-f运算符使您可以更好地控制生成的字符串表示,允许您执行诸如填充和选择浮点数的小数位数等操作。

但是请注意,这种方法仅适用于标量,而不适用于数组(集合)。


使用字符串连接( +):

"'" + $Test + "'"

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

这是字符串扩展的更详细的替代方法,使正在执行的操作更加明显。

于 2018-11-10T17:55:51.760 回答