[英]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. PowerShell允许您使用分号作为行终止符。
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. 另请注意,您可以将任意表达式构建为简单字符串,然后使用Invoke-Expression (别名iex
)来内联调用它。
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. 不过,这种方法非常简陋和脆弱,所以我不推荐它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.