powershellternary-operatornull-coalescing-operator

$prompt = ($defaultValue,$prompt)[[bool]$prompt] - emulating a ternary conditional in PowerShell


I'm learning to write scripts with PowerShell, and I found this code that will help me with a project The example comes from Is there a one-liner for using default values with Read-Host?.

$defaultValue = 'default'

$prompt = Read-Host "Press enter to accept the default [$($defaultValue)]"

$prompt = ($defaultValue,$prompt)[[bool]$prompt]

I think I understand that $prompt = ($defaultValue,$prompt) is creating a two-element array and that the [bool] part is forcing the $prompt data type to Boolean, but I don’t understand what this third line of code does as a whole.


Solution

  • Casting $prompt to [bool] produces a value of $true or $false depending on whether the variable is empty ($null or empty string both become $false) or not (non-emtpy strings become $true).

    [bool]''          → $false
    [bool]'something' → $true

    Using that boolean value in the index operator then implicitly casts the value to an integer where $false becomes 0 and $true becomes 1, hence selecting the first or second element of the array.

    [int]$false → 0
    [int]$true  → 1
    ($defaultValue,$prompt)[0] → $defaultValue
    ($defaultValue,$prompt)[1] → $prompt