function - 如何省略调用函数的$ null参数?

标签 function powershell arguments

考虑这样的功能:

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

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

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

我想这样调用这个函数
Test -foo $foo -bar $bar

但是,如果$ foo或$ bar为$ null,则会引发异常。天真的解决方案是
if($foo -and $bar)
{
  Test -foo $foo -bar $bar
}
elseif ($foo)
{
  Test -foo $foo
}
elseif ($bar)
{
  Test -bar $bar
}
else
{
  Test
}

我如何用一两行重写if / else块?

最佳答案

由于您无法控制“测试”功能,因此可以执行以下操作:

$params = @()
if ($foo) {
    $params += "-Foo","`$foo"
}
if ($bar) {
    $params += "-Bar","`$bar"
}
Invoke-Expression "Test $params"

关于function - 如何省略调用函数的$ null参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/728022/

相关文章:

python - 相同的函数在 Python 中以相反的顺序给出不同的结果。为什么?

powershell - 自动化配置SQL Server 2017 Reporting Services

windows - 如何将文字双引号从 PowerShell 传递到 native 命令?

c - 如何使用 SWIG 包装带有可变参数的 C 函数

c++ - 我可以在实际函数调用中将静态映射定义为函数参数吗?

javascript - 我的范围有什么问题?为什么我不覆盖变量? js

c++ - SFML 在另一个类中绘制移动 Sprite

python - 编写一个 pandas/python 函数,它需要在 pandas 数据框中输入多列

python - 为什么 pip 在 PyCharm 之外无法工作

c - 使用c中多维数组中的行的递归函数中的语法错误