PowerShell inline If (IIf)

后端 未结 7 1993
独厮守ぢ
独厮守ぢ 2020-12-07 16:24

How do I create an a statement with an inline If (IIf, see also: Immediate if or ternary If) in PowerShell?

If you also think that this should be a native Po

7条回答
  •  庸人自扰
    2020-12-07 16:56

    Powershell 7 allows ternary operators:

    $message = (Test-Path $path) ? "Path exists" : "Path not found"
    

    Earlier versions: PowerShell gives back values that haven't been assigned.

    $a = if ($condition) { $true } else { $false }
    

    Example:

    "The item is $(if ($price -gt 100) { 'expensive' } else { 'cheap' })"
    

    Let's try it out:

    $price = 150
    The item is expensive
    $price = 75
    The item is cheap
    

提交回复
热议问题