s3d83d
s3d83d

Reputation: 41

How to run if inline on PowerShell command

Suppose I have this function;

Function SomeCommand{
    param(
        [string]$Var1,
        [string]$Var2
    )

    # Do Something
}

I could set it up like this;

Function SomeCommand{
    param(
        [string]$Var1,
        [string]$Var2
    )

    if ($Var2){
        Do-SomeOtherCommand -SomeParam1 $Var1 -SomeParam2 $Var2
    } else {
        Do-SomeOtherCommand -SomeParam1 $Var1
}

This works fine if I only have one optional parameter, but if I have two it gets harry. I would like to do something like this;

Function SomeCommand{
    param(
        [string]$Var1,
        [string]$Var2,
        [string]$Var3
    )

    Do-SomeOtherCommand -SomeParam1 $Var1 (if($Var2){-SomeParam2 $Var2}) (if($Var3){-SomeParam3 $Var3})
}

Is there a way to accomplish this?

Upvotes: 1

Views: 1241

Answers (3)

latkin
latkin

Reputation: 16812

Also note that you can build up an arbitrary expression as a simple string, then use Invoke-Expression (alias iex) to invoke it inline.

function FuncB($param1, $param2)
{
   "FuncB -- param1:[$param1] param2:[$param2]"
}

function FuncA($paramA, $paramB)
{
  $funcBCall = "FuncB $(if($paramA){ "-param1 '$paramA'" }) $(if($paramB){ "-param2 '$paramB'" })"
  iex $funcBCall
}

This approach is very hacky and brittle, though, so I wouldn't recommend it.

Upvotes: 0

latkin
latkin

Reputation: 16812

You are probably looking for splatting. You can build up a hashtable with the parameters you wish to pass (and their values), then specify the whole thing in one shot:

function FuncB($param1, $param2)
{
   "FuncB -- param1:[$param1] param2:[$param2]"
}

function FuncA($paramA, $paramB)
{
   $args = @{}
   if ($paramA){ $args['param1'] = $paramA }
   if ($paramB){ $args['param2'] = $paramB }

   FuncB @args
}

Test

FuncA 'first' 'second'
FuncA 'OnlyFirst'
FuncA -paramB 'OnlySecond'

# results
# FuncB -- param1:[first] param2:[second]
# FuncB -- param1:[OnlyFirst] param2:[]
# FuncB -- param1:[] param2:[OnlySecond]

Upvotes: 3

Bacon Bits
Bacon Bits

Reputation: 32220

Semicolons. PowerShell allows you to use semicolons as line terminators.

Write-Output 1;Write-Output 2;Write-Output 3;

Personally, I think it should be mandatory.

Upvotes: 0

Related Questions