7

我一直在尝试使用 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
4

1 回答 1

6

为此,您可以使用我称之为“CallStack peeking”的技术。使用 Get-PSCallStack 查看调用该函数的任何内容。每个项目都有一个 InvocationInfo,其中一个名为“BoundParameters”的属性。这具有@每个级别的参数。如果 -WhatIf 被传递给其中任何一个,你可以像 -WhatIf 被传递给你的函数一样。

希望这可以帮助

于 2011-11-02T19:29:04.497 回答