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検索では解決できません。連結する方法はわかります。定数 そして 変数しかし、定数と式を連結する方法については何も説明されていないようです。

正しい方向を教えていただけますか?

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

関連情報