2011-11-02 21 views
7

我一直在嘗試編寫安全代碼,以支持-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 
+0

以我的經驗,通過直通普通參數'-WhatIf即便:$ WHATIF -Confirm:$確認-Debug:$調試-Verbose:$ Verbose',他們將跨忽略 - 模塊邊界... –

回答

6

要做到這一點,你可以使用的技術我稱之爲 「調用堆棧偷看」。使用Get-PSCallStack查看所謂的函數。每個項目都有一個InvocationInfo,裏面有一個名爲「BoundParameters」的屬性。這有每個級別的參數。如果-WhatIf被傳遞給它們中的任何一個,則可以像-WhatIf那樣傳遞給你的函數。

希望這有助於

+0

這種方法很快就會導致細微的缺陷。當指定'-WhatIf'或'-Confirm'時會發生什麼情況,但是調用堆棧中間的函數具有不需要使用'-WhatIf'的邏輯?你是否會查找所有其他常見參數,例如'-Verbose','-Debug'?引入新的通用參數時會發生什麼?您是否考慮了全球$ ConfirmPreference值? –

相關問題