views:

167

answers:

3

Consider such function:

$missed = "{716C1AD7-0DA6-45e6-854E-4B466508EB96}"

function Test($foo = $missed, $bar = $missed)
{
  if(!$foo)
  {
    throw "error"
  }

  if(!$bar)
  {
    throw "error"
  }
}

I whould like to call this function this way

Test -foo $foo -bar $bar

But if $foo or $bar is $null, exception will be thrown. The naive solution is

if($foo -and $bar)
{
  Test -foo $foo -bar $bar
}
elseif ($foo)
{
  Test -foo $foo
}
elseif ($bar)
{
  Test -bar $bar
}
else
{
  Test
}

How can I rewrite this if/else block in one/two lines?

+1  A: 

You could write the function as -

if (!$foo) {$foo = $missed}
if (!$bar) {$bar = $missed}

Mohit Chakraborty
Actually I have no access to Test function implementation and $missed variable. It was just an illustration. I just know that this function throws error when either parameter is $null
alex2k8
Then, if you know what the function sets the missing value to ($missing), can you set them before calling it, meaning the 2 ifs written above go before the function call.
Mohit Chakraborty
+3  A: 

Since you have no control over the Test function, then you could do this:

$params = @()
if ($foo) {
    $params += "-Foo","`$foo"
}
if ($bar) {
    $params += "-Bar","`$bar"
}
Invoke-Expression "Test $params"
JasonMArcher
A: 
function m ($x) {if ($x) {$x} else {$missed}}

Test -foo (m $foo) -bar (m $bar)
dangph