7

私は、ShouldProcessメソッドを使用して-whatifをサポートする安全なコードを作成しようとしてきました。これにより、ユーザーは、コマンドレットを実際に実行する前に、コマンドレットが何を実行するかを理解できます。

しかし、私はちょっとした問題に遭遇しました。-whatifを引数としてスクリプトを呼び出すと、$pscmdlet.ShouldProcessはfalseを返します。すべてうまくいっています。同じファイル(SupportsShouldProcess = $ trueを持つ)で定義されたコマンドレットを呼び出すと、falseも返されます。

ただし、Import-Moduleを使用してロードした別のモジュールで定義されたコマンドレットを呼び出すと、trueが返されます。-whatifコンテキストは、他のモジュールの呼び出しに渡されていないようです。

すべてのコマンドレットに手動でフラグを渡す必要はありません。誰かがより良い解決策を持っていますか?

この問題は、この質問に関連しているようです。ただし、モジュール間の問題については話していません。

スクリプト例:

#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

これを行うには、私が「CallStackpeeking」と呼ぶ手法を使用できます。Get-PSCallStackを使用して、関数と呼ばれるものを検索します。各アイテムにはInvocationInfoがあり、その内部には「BoundParameters」というプロパティがあります。これには、各レベルのパラメーターがあります。-WhatIfがそれらのいずれかに渡された場合、関数に-WhatIfが渡されたように動作できます。

お役に立てれば

于 2011-11-02T19:29:04.497 に答える