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

(我嘗試過不帶括號(...):同樣的錯誤。)顯然我做錯了什麼,但我的 google-fu 今天沒有幫助。我可以看到如何連接常量 變數,但似乎沒有解釋如何連接常數和表達式。

您能給我指出正確的方向嗎?

答案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" }))

相關內容