Search code examples
powershellpowershell-6.0

Elegant way of setting default value for variable in Powershell 6.0?


I have the following, which works but looks clunky:

if($config.contentDir){ 
    $contentDir = $config.contentDir
} else { 
    $contentDir = "contents"
}

Is there a nicer way of doing this? I have seen this answer here, but it isn't exactly "nicer". Just wondering if 6.0 brought any improvements?

I'm likely to be handling a large amount of config options, so it's going to get fairly messy.


Solution

  • This is a little shorter...

    $contentDir = if ( $config.contentDir ) { $config.contentDir } else { "contents" }
    

    You could also define an iif function:

    function iif {
      param(
        [ScriptBlock] $testExpr,
        [ScriptBlock] $trueExpr,
        [ScriptBlock] $falseExpr
      )
      if ( & $testExpr ) {
        & $trueExpr
      }
      else {
        & $falseExpr
      }
    }
    

    Then you could shorten to this:

    $contentDir = iif { $config.contentDir } { $config.contentDir } { "contents" }
    

    As an aside, it looks like the next version of PowerShell will support the ternary operator (see https://devblogs.microsoft.com/powershell/powershell-7-preview-4/), so in the future, you'll be able to write something like:

    $contentDir = $config.contentDir ? $config.contentDir : "contents"