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

관련 정보