PowerShell의 3진 연산자
제가 아는 바로는 PowerShell에는 이른바 3진 연산자에 대한 표현식이 내장되어 있지 않은 것 같습니다.
예를 들어, 3진 연산자를 지원하는 C 언어에서는 다음과 같이 쓸 수 있습니다.
<condition> ? <condition-is-true> : <condition-is-false>;
PowerShell에 실제로 존재하지 않는 경우 동일한 결과를 얻기 위한 가장 좋은 방법(읽기 쉽고 유지 보수하기 쉬운 방법)은 무엇입니까?
$result = If ($condition) {"true"} Else {"false"}
단순한 할당이 아닌 표현식 또는 표현식으로 사용하기 위해 로 감습니다.$()
다음과 같습니다.
write-host $(If ($condition) {"true"} Else {"false"})
파워셸 7이 가지고 있다.
PS C:\Users\js> 0 ? 'yes' : 'no'
no
PS C:\Users\js> 1 ? 'yes' : 'no'
yes
제가 에뮬레이트하기 위해 생각해낸 PowerShell의 가장 가까운 구조는 다음과 같습니다.
@({'condition is false'},{'condition is true'})[$condition]
대체 수단으로 powershell의 switch 문을 사용해 보십시오.특히 변수 할당의 경우 여러 줄이지만 읽을 수 있습니다.
예,
$WinVer = switch ( Test-Path -Path "$Env:windir\SysWOW64" ) {
$true { "64-bit" }
$false { "32-bit" }
}
"This version of Windows is $WinVer"
이 PowerShell 블로그 게시물에 따라 에일리어스를 생성하여?:
연산자:
set-alias ?: Invoke-Ternary -Option AllScope -Description "PSCX filter alias"
filter Invoke-Ternary ([scriptblock]$decider, [scriptblock]$ifTrue, [scriptblock]$ifFalse)
{
if (&$decider) {
&$ifTrue
} else {
&$ifFalse
}
}
다음과 같이 사용합니다.
$total = ($quantity * $price ) * (?: {$quantity -le 10} {.9} {.75})
PowerShell 버전 7부터는 3진 연산자가 PowerShell에 내장되어 있습니다.
1 -gt 2 ? "Yes" : "No"
# Returns "No"
1 -gt 2 ? 'Yes' : $null
# Get a $null response for false-y return value
저도 더 나은 답을 찾고 있었어요.에드워드의 투고에는 'OK'라는 답이 있었지만, 저는 이 블로그 투고에서 훨씬 더 자연스러운 해결책이 떠올랐습니다.
짧고 달콤함:
# ---------------------------------------------------------------------------
# Name: Invoke-Assignment
# Alias: =
# Author: Garrett Serack (@FearTheCowboy)
# Desc: Enables expressions like the C# operators:
# Ternary:
# <condition> ? <trueresult> : <falseresult>
# e.g.
# status = (age > 50) ? "old" : "young";
# Null-Coalescing
# <value> ?? <value-if-value-is-null>
# e.g.
# name = GetName() ?? "No Name";
#
# Ternary Usage:
# $status == ($age > 50) ? "old" : "young"
#
# Null Coalescing Usage:
# $name = (get-name) ? "No Name"
# ---------------------------------------------------------------------------
# returns the evaluated value of the parameter passed in,
# executing it, if it is a scriptblock
function eval($item) {
if( $item -ne $null ) {
if( $item -is "ScriptBlock" ) {
return & $item
}
return $item
}
return $null
}
# an extended assignment function; implements logic for Ternarys and Null-Coalescing expressions
function Invoke-Assignment {
if( $args ) {
# ternary
if ($p = [array]::IndexOf($args,'?' )+1) {
if (eval($args[0])) {
return eval($args[$p])
}
return eval($args[([array]::IndexOf($args,':',$p))+1])
}
# null-coalescing
if ($p = ([array]::IndexOf($args,'??',$p)+1)) {
if ($result = eval($args[0])) {
return $result
}
return eval($args[$p])
}
# neither ternary or null-coalescing, just a value
return eval($args[0])
}
return $null
}
# alias the function to the equals sign (which doesn't impede the normal use of = )
set-alias = Invoke-Assignment -Option AllScope -Description "FearTheCowboy's Invoke-Assignment."
이를 통해 다음과 같은 작업을 쉽게 수행할 수 있습니다(블로그 투고에서 더 많은 예 참조).
$message == ($age > 50) ? "Old Man" :"Young Dude"
일반적으로 값을 할당할 때 3진 연산자가 사용되므로 값을 반환해야 합니다.다음과 같이 동작합니다.
$var=@("value if false","value if true")[[byte](condition)]
멍청하지만, 효과가 있어.또한 이 구성을 사용하여 int를 다른 값으로 빠르게 변환할 수 있습니다. 배열 요소를 추가하고 0이 아닌 값을 반환하는 식을 지정할 수 있습니다.
PowerShell의 3진 연산자는 PowerShell 버전 7.0에서 도입되었습니다.
[Condition] ? (output if True) : (output if False)
예 01
$a = 5; $b = 6
($a -gt $b) ? "True" : "False"
산출량
False
예 02
($a -gt $b) ? ("$a is greater than $b") : ("$a is less than $b")
산출량
5 is less than 6
자세한 것은, https://www.tutorialspoint.com/how-ternary-operator-in-powershell-works 를 참조해 주세요.
이미 여러 번 사용했지만 여기에 나열되지 않았으므로 제 작품을 추가합니다.
$var = @{$true="this is true";$false="this is false"}[1 -eq 1]
제일 못생겼어!
최근 PoweShell lib 'Pscx'의 3진 조건부 연산자와 늘 결합 연산자를 개선(열기 PullRequest)했습니다.
제 해결책을 찾아보세요.
내 github 토픽 브랜치: 유틸리티 모듈_호출 연산자
기능:
Invoke-Ternary
Invoke-TernaryAsPipe
Invoke-NullCoalescing
NullCoalescingAsPipe
에일리어스
Set-Alias :?: Pscx\Invoke-Ternary -Description "PSCX alias"
Set-Alias ?: Pscx\Invoke-TernaryAsPipe -Description "PSCX alias"
Set-Alias :?? Pscx\Invoke-NullCoalescing -Description "PSCX alias"
Set-Alias ?? Pscx\Invoke-NullCoalescingAsPipe -Description "PSCX alias"
사용.
<condition_expression> |?: <true_expression> <false_expression>
<variable_expression> |?? <alternate_expression>
표현으로서 다음과 같이 패스할 수 있습니다.
$syslog, 리터럴, 변수, 'syslog' 식($b - eq 4) 또는 스크립트 블록 {$b - eq 4}
변수식 변수가 $null이거나 존재하지 않는 경우 대체식은 출력으로 평가됩니다.
PowerShell
현재는 없다 에는 네이티브 Inline If(또는 3진수 If)가 없지만 커스텀 cmdlet 사용을 고려할 수 있습니다.
IIf <condition> <condition-is-true> <condition-is-false>
자세한 내용은 PowerShell 인라인 If (IIF)를 참조하십시오.
부울 조건에 따라 문자열 또는 숫자를 할당/반환하는 구문적으로 단순한 방법을 찾는 경우 다음과 같이 곱셈 연산자를 사용할 수 있습니다.
"Condition is "+("true"*$condition)+("false"*!$condition)
(12.34*$condition)+(56.78*!$condition)
어떤 것이 참일 때만 결과에 관심이 있는 경우 잘못된 부분을 완전히 생략할 수 있습니다(또는 그 반대). 예를 들어 간단한 점수 매기기 시스템:
$isTall = $true
$isDark = $false
$isHandsome = $true
$score = (2*$isTall)+(4*$isDark)+(10*$isHandsome)
"Score = $score"
# or
# "Score = $((2*$isTall)+(4*$isDark)+(10*$isHandsome))"
부울 값은 곱셈의 선두 용어가 되어서는 안 됩니다.즉, $condition*"true" 등은 동작하지 않습니다.
다음은 대체 커스텀 기능 접근법입니다.
function Test-TernaryOperatorCondition {
[CmdletBinding()]
param (
[Parameter(ValueFromPipeline = $true, Mandatory = $true)]
[bool]$ConditionResult
,
[Parameter(Mandatory = $true, Position = 0)]
[PSObject]$ValueIfTrue
,
[Parameter(Mandatory = $true, Position = 1)]
[ValidateSet(':')]
[char]$Colon
,
[Parameter(Mandatory = $true, Position = 2)]
[PSObject]$ValueIfFalse
)
process {
if ($ConditionResult) {
$ValueIfTrue
}
else {
$ValueIfFalse
}
}
}
set-alias -Name '???' -Value 'Test-TernaryOperatorCondition'
예
1 -eq 1 |??? 'match' : 'nomatch'
1 -eq 2 |??? 'match' : 'nomatch'
차이점 설명
- 1번, 3번?
?
입니다.Where-Object
.??
다른 언어에서는 늘 병합 연산자로 사용되고 있기 때문에 혼란을 피하고 싶었습니다.
- 령령전 파이 ?이? 이???
- 파이프라인을 사용하여 평가하고 있기 때문에 상태를 함수에 연결하려면 이 캐릭터가 여전히 필요합니다.
- 열로 통통 ?떻 떻? ???
- 수 . 각 값에 대한 결과를 얻을 수 .
-2..2 |??? 'match' : 'nomatch'
match, match, nomatch, match, match
(의 int는 (0의 int int int > )로true
; 단, 은 ;, 0, 0으로false
를 참조해 주세요. - 원하지 않으면 불(bool한다.
([bool](-2..2)) |??? 'match' : 'nomatch'
간단히:)[bool](-2..2) |??? 'match' : 'nomatch'
)
- 수 . 각 값에 대한 결과를 얻을 수 .
언급URL : https://stackoverflow.com/questions/31341998/ternary-operator-in-powershell
'programing' 카테고리의 다른 글
PowerShell 스크립트 종료 (0) | 2023.04.08 |
---|---|
같은 프로젝트에서 C#과 VB의 혼재 (0) | 2023.04.08 |
PowerShell 모듈이 장착되어 있는지 확인하는 방법 (0) | 2023.04.08 |
부유 원소의 부모가 무너지지 않게 하려면 어떻게 해야 하나요? (0) | 2023.04.08 |
div의 내용을 맨 아래에 정렬하는 방법 (0) | 2023.04.08 |