私は、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