Thursday, July 3, 2014

Ternary operation powershell

I googled for ternary operation in powershell and found basically nothing, at least nothing good. It's seems like operations is not supported out of the box. There is a suggestion how it can be done using hash table.
Something like this:


$x = @{$true=10; $false=5}[$y % 2 -eq 0]

We just create a hash table with 2 boolean keys and then in accessor block evaluate condition.
In order to make it clear it might be simplified like that:


$key = $y % 2 -eq 0
$values = @{$true=10; $false=5}
$x = $values[$key]

Works fine but in my opinion not easy to read. It's always possible to invent a wheel. To add some custome function, I created that one:


function when {
 Param(
  [bool]$expression = $(throw "Boolean expression is required"),
  $then = $(throw "-then value is required"),
  $otherwise = $(throw "-otherwise value is required")
 )
 
 if ($expression) {
  return $then
 }
 
 return $otherwise
}

Here is an example of usage


$x = when ($y % 2 -eq 0) -then 10 -otherwise 5

I think it quite easy to read, but there is one thing that I really don't want to do, to add this function to every place where I need. In case you have many scripts and some script with the common stuff like Common.ps1, then maybe it's ok, since Common.ps1 is already linked everywhere. But it would be really nice to have something simple. And there is an option. Thing is that keyword return in powershell is not so required. Both function bellow return the same value:


function f1() {
 return 10
}

function f2() {
 10
}

Now let's try to think about obvious way how to deal with conditional logic. There is IF statement. So we can set a variable like that:

if ($y % 2 -eq 0) {
 $x = 10
} else {
 $x = 5
}

Let's improve it:


$x = if ($true) {
 return 10
} else {
 return 5
}

And the last improvement:


$x = if ($true) { 10 } else { 5 }

quite simple and no additional function is required. And it supports evaluation of some complex functions:


$z = if ($true) { someFunction $y $x } else { otherFunction $y $x }

1 comment:

  1. Casino Site | The Closest Casino To Chicago
    The 메리트 카지노 쿠폰 casino is located in the heart of Chicago, 카지노사이트 near The Art Museum and University of Chicago. It is home to over 2000 games, a casino, and a poker room. septcasino

    ReplyDelete