使用PowerShell,如何让Write-Debug输出出现在控制台中?

Ken*_*mer 16 powershell

我正在学习PowerShell,并且正在使用Write-Host检查新PowerShell脚本文件中的变量赋值.然后我读了这篇文章:http: //windowsitpro.com/blog/what-do-not-do-powershell-part-1

所以,在我的.ps1文件中,我替换了这样的语句:

Write-Host "Start"
Write-Host "End"
Run Code Online (Sandbox Code Playgroud)

... 有了这个:

Write-Debug "Start"
Write-Debug "End"
Run Code Online (Sandbox Code Playgroud)

但是当我在Windows PowerShell ISE中运行保存的脚本时,没有输出写入控制台.我将-debug附加到调用脚本的语句中,如下所示:

PS E:\trialrun> .\MyScript.ps1 -debug
Run Code Online (Sandbox Code Playgroud)

但同样,输出不会写入控制台.显然我正在使用Write-Debug错误.如何将调试输出写入控制台?谢谢.

mkl*_*nt0 26

tl;博士:

  • 运行$DebugPreference = 'Continue'以开始查看来自Write-Debug呼叫的输出.

  • 完成后,使用将恢复首选项变量恢复$DebugPreference为默认值$DebugPreference = 'SilentlyContinue'


是否Write-Debug打印语句的输出由两种机制控制:

$DebugPreference默认为SilentlyContinue,这解释了为什么Write-Debug默认情况下您没有看到语句的任何输出.

当你使用common参数时-Debug,你基本上$DebugPreference 只为被调用的命令设置,并且你总是将它设置为值Inquire,这不仅会打印 Write-Debug消息,还会在每个这样的语句中暂停,以询问你想如何继续.

  • 对于支持Continue公共参数的自定义脚本或函数,必须使用-Debug[CmdletBinding()]块的属性声明它,如Mathias的答案所示.

由于这种即时param()通知行为可能具有破坏性,因此Write-Debug可能是更好的方法.

  • 谢谢。这是一个很酷的方法。我不知道参数可以查询这样的键。相反,我实际上最终编写了一个 if ($DebugPreference -eq 'Inquire' ) 语句进行检查,然后 if true 设置 $DebugPreference = 'Continue' 如果客户端始终拥有 PS6,则会更容易。 (2认同)

Mat*_*sen 11

CmdletBinding如果要支持常用参数(包括-Debug),则需要脚本中的属性:

[CmdletBinding()]
param()

Write-Debug Start
Write-Debug End
Run Code Online (Sandbox Code Playgroud)

我建议看看about_Functions_CmdletBindingAttribute帮助文件

  • 一般来说,这是一个很好的建议,但是,与其他常见参数(例如“-ErrorAction”)不同,“-Debug”不允许您为隐含的命令范围“$DebugPreference”变量传递_特定值_,而是总是设置它到“查询”,这意味着遇到的每个“写入调试”语句都会“提示”,如果您的唯一目的是“打印”调试消息,这会造成破坏。 (2认同)