2013-05-06 101 views
6

我希望在腳本和函數中使用Write-Verbose命令行開關。它在腳本(.ps1)文件中按預期方式工作,但不在模塊(.psm1)文件中 - 模塊中將忽略該命令行開關。在PowerShell模塊中忽略了Write-Verbose

運行下面的腳本:

PS> .\scaffold.ps1 -verbose 

產地:

VERBOSE: starting foo 
path: c:\bar.txt 
[missing entry here - 'verbose path: c:\bar.txt'] 
VERBOSE: ending foo 

scaffold.ps1:

[cmdletbinding()] 
param() 

import-module Common -force 

write-verbose "starting foo" 

foo "c:\bar.txt" 

write-verbose "ending foo" 

Common.psm1:

function foo { 

    [cmdletbinding()] 
    Param(
    [string]$path 
) 

    write-host "path: $path" 
    write-verbose "verbose path: $path" 

} 

在這一點上我沒有關聯一個清單(.psd1)和模塊(.psm1)。

是否有我需要使用的模塊特定語法?

**編輯**

我需要的是一種方法來確定是否-verbose標誌已在.PS1文件中設置這樣我就可以把它傳遞給名爲.psm1文件。

scaffold.ps1:

[cmdletbinding()] 
param() 

import-module Common -force 

write-verbose "starting foo" 

foo "c:\bar.txt" $verbose_flag # pass verbose setting to module based on what was set on the script itself 

write-verbose "ending foo" 

回答

4

找到答案在這裏:How to properly use the -verbose and -debug parameters in custom cmdlet

scaffold.ps1:

[cmdletbinding()] 
param() 

import-module Common -force 

write-verbose "starting foo" 

foo "c:\bar.txt" -Verbose:($PSBoundParameters['Verbose'] -eq $true) 

write-verbose "ending foo" 
+0

感謝分享;同意這似乎是唯一可行的;但它聞起來不好...因爲這有一個功能建議。對於PowerShell atm,MS Connect已禁用,因此現在已經發布了博文:https://developer42.wordpress.com/2017/02/04/powershell-suggestion-simplify-write-verbose-in-modules/ – JohnLBevan 2017-02-04 10:45:55

+0

更新:記錄爲問題在PowerShell的GitHub頁面上:https://github.com/PowerShell/PowerShell/issues/3106 – JohnLBevan 2017-02-07 09:51:44

5

要想從一個cmdlet的Write-Verbose輸出模塊中,你需要使用-verbose常見的參數。見http://technet.microsoft.com/en-us/magazine/ff677563.aspx

使用代碼:

>import-module R:\Common.psm1 
>foo "c:\users" 
path: c:\users 
>foo "c:\users" -verbose 
path: c:\users 
VERBOSE: verbose path: c:\users 
+0

這一工作進行下載。不能相信我沒有想到... – craig 2013-05-06 20:58:12

+1

在.ps1文件本身中是否存在作爲變量可用的-verbose切換鍵? 'foo「c:\ bar.txt」$ verbose「或類似的東西? – craig 2013-05-07 23:46:58

+0

我不能從文檔中知道。爲什麼你需要測試它?只要使用'Write-Verbose' - 如果使用'-verbose',它將產生輸出,否則它將保持沉默。 – alroc 2013-05-08 00:45:00

3

這裏的問題是,在主叫方的範圍變量不通過腳本模塊中的代碼獲取。當您調用「。\ scaffold.ps1 -verbose」時,$ scbpPreference在scaffold.ps1的腳本範圍中設置爲「繼續」。如果您從該腳本中調用編譯的Cmdlet,它會承認$ VerbosePreference的值,但是當您從腳本模塊調用高級函數時,它們不會。

我最近編寫了一個函數,允許您使用$ PSCmdlet和$ ExecutionContext.SessionState的組合來從調用者中導入首選項變量以獲取適當的變量作用域。這個命令的調用,在腳本模塊的導出函數的開頭,看起來是這樣的:

Get-CallerPreference -Cmdlet $PSCmdlet -SessionState $ExecutionContext.SessionState 

一開始CallerPreference功能可以從http://gallery.technet.microsoft.com/scriptcenter/Inherit-Preference-82343b9d