简体   繁体   中英

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?

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]

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM