我一直在尝试使用 ShouldProcess 方法编写支持 -whatif 的安全代码,以便我的用户在真正运行 cmdlet 之前了解它应该做什么。
但是,我遇到了一些障碍。如果我以 -whatif 作为参数调用脚本,$pscmdlet.ShouldProcess 将返回 false。一切都很好。如果我调用在同一文件中定义的 cmdlet(具有 SupportsShouldProcess=$true),它也会返回 false。
但是,如果我调用在使用 Import-Module 加载的另一个模块中定义的 cmdlet,它将返回 true。-whatif 上下文似乎没有传递给另一个模块中的调用。
我不想手动将标志传递给每个 cmdlet。有没有人有更好的解决方案?
这个问题似乎与这个问题有关。但是,他们不是在谈论跨模块问题。
示例脚本:
#whatiftest.ps1
[CmdletBinding(SupportsShouldProcess=$true)]
param()
Import-Module -name .\whatiftest_module -Force
function Outer
{
[CmdletBinding(SupportsShouldProcess=$true)]
param()
if( $pscmdlet.ShouldProcess("Outer"))
{
Write-Host "Outer ShouldProcess"
}
else
{
Write-Host "Outer Should not Process"
}
Write-Host "Calling Inner"
Inner
Write-Host "Calling InnerModule"
InnerModule
}
function Inner
{
[CmdletBinding(SupportsShouldProcess=$true)]
param()
if( $pscmdlet.ShouldProcess("Inner"))
{
Write-Host "Inner ShouldProcess"
}
else
{
Write-Host "Inner Should not Process"
}
}
Write-Host "--Normal--"
Outer
Write-Host "--WhatIf--"
Outer -WhatIf
模块:
#whatiftest_module.psm1
function InnerModule
{
[CmdletBinding(SupportsShouldProcess=$true)]
param()
if( $pscmdlet.ShouldProcess("InnerModule"))
{
Write-Host "InnerModule ShouldProcess"
}
else
{
Write-Host "InnerModule Should not Process"
}
}
输出:
F:\temp> .\whatiftest.ps1
--Normal--
Outer ShouldProcess
Calling Inner
Inner ShouldProcess
Calling InnerModule
InnerModule ShouldProcess
--WhatIf--
What if: Performing operation "Outer" on Target "Outer".
Outer Should not Process
Calling Inner
What if: Performing operation "Inner" on Target "Inner".
Inner Should not Process
Calling InnerModule
InnerModule ShouldProcess