測試腳本:PowerShell腳本:當函數調用嵌套時推薦的方式來實現ShouldProcess?
function outer
{
[cmdletbinding(supportsshouldprocess=$true)]
param($s)
process
{
$pscmdlet.shouldprocess("outer $s", "ShouldProcess") | out-null
"" | out-file "outer $s"
inner ImplicitPassthru
inner VerbosePassthru -Verbose:$Verbose
inner WhatifPassthru -WhatIf:$WhatIf
}
}
function inner
{
[cmdletbinding(supportsshouldprocess=$true)]
param($s)
process
{
$pscmdlet.shouldprocess("inner $s", "ShouldProcess") | out-null
"" | out-file "inner $s"
}
}
"`n** NORMAL **"
outer normal
"`n** VERBOSE **"
outer verbose -Verbose
"`n** WHATIF **"
outer whatif -WhatIf
輸出:
** NORMAL **
VERBOSE: Performing operation "ShouldProcess" on Target "inner VerbosePassthru".
What if: Performing operation "ShouldProcess" on Target "inner WhatifPassthru".
What if: Performing operation "Output to File" on Target "inner WhatifPassthru".
** VERBOSE **
VERBOSE: Performing operation "ShouldProcess" on Target "outer verbose".
VERBOSE: Performing operation "ShouldProcess" on Target "inner VerbosePassthru".
What if: Performing operation "ShouldProcess" on Target "inner WhatifPassthru".
What if: Performing operation "Output to File" on Target "inner WhatifPassthru".
** WHATIF **
What if: Performing operation "ShouldProcess" on Target "outer whatif".
What if: Performing operation "Output to File" on Target "outer whatif".
What if: Performing operation "ShouldProcess" on Target "inner ImplicitPassthru".
What if: Performing operation "Output to File" on Target "inner ImplicitPassthru".
What if: Performing operation "ShouldProcess" on Target "inner VerbosePassthru".
What if: Performing operation "Output to File" on Target "inner VerbosePassthru".
What if: Performing operation "ShouldProcess" on Target "inner WhatifPassthru".
What if: Performing operation "Output to File" on Target "inner WhatifPassthru".
爲了我的眼睛有下面介紹幾種奇特:
- 指定-WhatIf:$ foo將總是接通$ WHATIF在被調用者(及其被調用者)中,不管$ foo是什麼。
- 當您確實指定-WhatIf「for real」(不限制它到現有變量)時,它會隱式傳播給被調用者。無需中繼或潑濺。
- 與-WhatIf不同,顯式-Verbose不隱式地級聯到被調用者。
- 當您嘗試手動passthru -Verbose:$ foo時,您看到的行爲與-WhatIf:$ foo類似。但它隻影響手動測試$ psCmdlet.ShouldProcess() - 內建在cmdlet中的腳本不受影響。
N.B.:確認行爲與WhatIf相同。爲了簡潔起見,我省略了它。
在Web和Connect的搜索中,我幾乎沒有深入討論與高級函數有關的ShouldProcess行爲(pro或con)。最接近的是a post from James O'Neill,建議在整個調用堆棧中傳遞$ psCmdlet的單個實例。但是,他這樣做是爲了解決完全不同的問題(避免多個-Confirm提示)。同時,當您堅持提供給每個功能的標準$ psCmdlet時,我看不到有什麼期望的文檔...更少的設計模式,最佳實踐等等......
的Bug提交:https://connect.microsoft.com/PowerShell/feedback/details/535559/shouldprocess-cmdlets-the-verbose-preference-is-not-evaluated-in-callees強制轉換爲空 - >真也是一個錯誤IMO,因爲它不會發生正常的開關參數。分別歸檔@ https://connect.microsoft.com/PowerShell/feedback/details/535557/shouldprocess-synthetic-parameters-should-not-coerce-null-true – 2010-02-23 08:17:20
已投票。感謝您提交這些文件。 – 2010-02-24 18:34:52
好工作的傢伙。 – JasonMArcher 2010-02-28 04:25:13