Powershell-String-Verkettung von Ausdrücken

Powershell-String-Verkettung von Ausdrücken

Ich verwende einen ternären Ausdruck, wie in diesem Beispiel gezeigt:

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

Das funktioniert wie erwartet. In meiner tatsächlichen Situation möchte ich jedoch direkt an zuweisen, $tohne den Zwischenschritt, den Ausdruck zuerst an zuzuweisen $x, als ob ich Folgendes tun könnte:

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

Ich erhalte jedoch einen Fehler in der Zuweisungszeile.

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

(Ich habe es mit und ohne Klammern versucht (...): derselbe Fehler.) Offensichtlich mache ich etwas falsch, aber mein Google-Fu hilft mir heute nicht weiter. Ich kann sehen, wie manKonstanten Und Variablen, aber es scheint nichts zu erklären, wie Konstanten und Ausdrücke verkettet werden.

Können Sie mir bitte den richtigen Weg weisen?

Antwort1

Du bistAlsoschließen. :)

Du brauchstverwenden Sie die$um den Rückgabewert der Anweisung als Variable zu deklarieren.

Also:

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

Oder vielleicht als zwei Zeilen, unter Verwendung von Write-HostsFormatierungsoptionen:

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

verwandte Informationen