alex2k8
alex2k8

Reputation: 43204

How to omit $null arguments calling a function?

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?

Upvotes: 1

Views: 405

Answers (4)

Paul Moore
Paul Moore

Reputation: 7259

You could use "splatting" as follows:

$params = @{}
if ($foo) {$params['foo'] = $foo}
if ($bar) {$params['bar'] = $bar}
Test @params

It's not much shorter, but it's a generally useful trick.

Upvotes: 1

dan-gph
dan-gph

Reputation: 16909

function m ($x) {if ($x) {$x} else {$missed}}

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

Upvotes: 2

JasonMArcher
JasonMArcher

Reputation: 15011

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"

Upvotes: 3

Mohit Chakraborty
Mohit Chakraborty

Reputation: 1263

You could write the function as -

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

Upvotes: 1

Related Questions