根据 power shell 团队的博客(下面的链接),从 V2 开始就有一种称为 splatting 的技术。基本上,您使用自动变量@PsBoundParameters 来转发所有参数。 Microsoft Docs 文章(下面的链接)中解释了有关喷溅的详细信息以及 @ 和 $ 之间的区别。
例子:
父.ps1
#Begin of parent.ps1
param(
[Switch] $MySwitch
)
Import-Module .\child.psm1
Call-Child @psBoundParameters
#End of parent.ps1
child.psm1
# Begin of child.psm1
function Call-Child {
param(
[switch] $MySwitch
)
if ($MySwitch){
Write-Output "`$MySwitch was specified"
} else {
Write-Output "`$MySwitch is missing"
}
}
#End of child.psm1
现在我们可以使用或不使用开关来调用父脚本
PS V:\sof\splatting> .\parent.ps1
$MySwitch is missing
PS V:\sof\splatting> .\parent.ps1 -MySwitch
$MySwitch was specified
PS V:\sof\splatting>
更新
在我最初的答案中,我采购了孩子而不是将其作为模块导入。似乎将另一个脚本采购到原始脚本中只会使父级的变量对所有子级可见,因此这也将起作用:
# Begin of child.ps1
function Call-Child {
if ($MySwitch){
Write-Output "`$MySwitch was specified"
} else {
Write-Output "`$MySwitch is missing"
}
}
#End of child.ps1
与
#Begin of parent.ps1
param(
[Switch] $MySwitch
)
. .\child.ps1
Call-Child # Not even specifying @psBoundParameters
#End of parent.ps1
也许,这不是制作程序的最佳方式,但是,这就是它的工作方式。
About Splatting(Microsoft Docs)
How and Why to Use Splatting (passing [switch] parameters)