Powershell 表达式的字符串连接

Powershell 表达式的字符串连接

我使用三元表达式,如本例所示:

$a = 1
$x = if ($a -eq 1) { "one" } else {"not one" }
$t = "The answer is: " + $x
write-host $t

这正如我所料。但在实际情况下,我希望直接将 分配给 ,$t而不需要先将表达式分配给 的中间步骤$x,就好像我可以这样做一样:

$a = 1
$t = "The answer is: " + (if ($a -eq 1) { "one" } else {"not one" })
write-host $t

然而,我在分配行上收到一个错误,

if : The term 'if' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the
spelling of the name, or if a path was included, verify that the path is correct and try again.
At line:1 char:31
+     $t = "The answer is: " + (if ($a -eq 1) { "one" } else {"not one" ...
+                               ~~
    + CategoryInfo          : ObjectNotFound: (if:String) [], CommandNotFoundException
    + FullyQualifiedErrorId : CommandNotFoundException

(我尝试过使用不带括号的(...):同样的错误。)显然我做错了什么,但我的谷歌搜索今天没用。我知道如何连接常量 变量,但似乎没有什么可以解释如何连接常量和表达式。

您能给我指明正确的方向吗?

答案1

你是所以关闭。 :)

你需要使用$将语句的返回值声明为变量。

所以:

$a = 1
$t = "The answer is: " + $(if ($a -eq 1) { "one" } else { "not one" })
write-host $t

或者可能分为两行,利用 Write-Host 的格式化选项

$a = 1
write-host ("{0} {1}" -f "The answer is:", $(if ($a -eq 1) { "one" } else { "not one" }))

相关内容