我一直在嘗試編寫安全代碼,以支持-Whatif與ShouldProcess方法,以便我的用戶瞭解在運行cmdlet之前應該做什麼它是真實的。Powershell:如何獲得-whatif在另一個模塊中傳播到cmdlet
但是我遇到了一點障礙。如果我用-whatif作爲參數調用腳本,$ pscmdlet.ShouldProcess將返回false。一切都很好。如果我調用在同一文件中定義的cmdlet(即SupportsShouldProcess = $ true),它也會返回false。
但是,如果我調用另一個模塊中定義的cmdlet,並使用Import-Module加載,它將返回true。 -whatif上下文似乎不會傳遞給其他模塊中的調用。
我不想手動將標誌傳遞給每個cmdlet。有沒有人有更好的解決方案?
此問題似乎與此question有關。但是,他們並不是在談論跨模塊問題。
示例腳本:
#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
以我的經驗,通過直通普通參數'-WhatIf即便:$ WHATIF -Confirm:$確認-Debug:$調試-Verbose:$ Verbose',他們將跨忽略 - 模塊邊界... –