2014-01-17 64 views
4

我有一个PowerShell脚本,我已将$DebugPreference设置为"Continue"。但是,当我从脚本中调用的模块调用Write-Debug时,$DebugPreference更改为"SilentlyContinue"。这是为什么?我如何保持$DebugPreference与调用脚本相同?实施例下面

CallingScript.ps1

$DebugPreference = "Continue" 
Write-Host "Debug preference: $DebugPreference" 
Write-Debug "Checking that debugging works" 
Import-Module Logging; 
Write-Log "Debug" "Checking that debugging still works!" 

Logging.psm1

Function Write-Log 
{ 
    param (
    [ValidateSet("Error","Warning","Debug","Info")][String]$type, 
    [String]$logMessage 
    ) 
    Write-Host "Debug preference: $DebugPreference" 
    switch($type) 
    { 
     "Error" {Write-Error $logMessage;} 
     "Warning" {Write-Warning $logMessage;} 
     "Debug" {Write-Debug $logMessage;} 
     "Info" {Write-Output $logMessage;} 

    } 
} 

如果我运行脚本,这是输出:

PS > .\CallingScript.ps1 
Debug preference: Continue 
DEBUG: Checking that debugging works 
Debug preference: SilentlyContinue 
PS > 
+3

这可以通过模块范围来解释。看看[这个答案](http://stackoverflow.com/a/17112513/608772)。我不想重复这个答案。如果它解释了你的问题,我会做。 – JPBlanc

+0

@JBBlanc您可能需要解释它并显示一个可行的例子...对不起! –

回答

5

作为JPBlanc's link在他的评论中解释说:这是一个可变范围问题。模块的作用域链直接进入全局作用域,而不是通过任何脚本作用域。即使它是从脚本导入的。如果从在全球范围内你的脚本设置$ DebugPreference

module scope

您的代码将工作,但当然,这对不只是你的脚本更大的影响力。

$global:DebugPreference = "Continue" 

在这个特定的$ DebugPreference情况下的另一个解决方案是使用-Debug参数传递它。缺点是你必须用你打的每个命令来做到这一点。

Write-Log "Debug" "Checking that debugging still works!" -debug:$DebugPreference 

A third solution将在模块级设置$ DebugPreference。

$m = Import-Module Logging -PassThru 
& $m {$script:DebugPreference = 'Continue'} 
+0

'$ script:DebugPreference =“Continue”似乎也起作用。我仍然了解范围... –

+0

$ script:DebugPreference在您的脚本中不起作用。如果您在全局范围内更改了DebugPreference之后对其进行测试,则可能看起来如此。开始一个新的PowerShell,并再次尝试。 –

+0

我一直在阅读关于范围。因此,如果我的脚本设置了'$ script:DebugPreference',那么所有被调用的模块将'$ DebugPreference'设置为'$ script:DebugPreference'。为什么我需要将其设置在全球范围内?我在一个新的Powershell窗口中测试过,它似乎工作正常。 –