使用PowerShell,如何让写调试输出显示在控制台中?

dphi5xsq  于 2023-06-23  发布在  Shell
关注(0)|答案(3)|浏览(241)

我正在学习PowerShell,并使用Write-Host检查新PowerShell脚本文件中的变量赋值。后来我读了一篇文章,说这是个坏主意。
所以,在我的.ps1文件中,我替换了这样的语句:

Write-Host "Start"
Write-Host "End"

。。。用这个:

Write-Debug "Start"
Write-Debug "End"

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

PS E:\trialrun> .\MyScript.ps1 -debug

但同样,输出不会写入控制台。显然,我错误地使用了写调试。我如何获得调试输出以写入控制台?

whlutmcx

whlutmcx1#

    • tl; dr**:
  • 运行$DebugPreference = 'Continue'开始查看Write-Debug调用的输出。
  • 完成后,使用$DebugPreference = 'SilentlyContinue'将首选项变量$DebugPreference恢复为其默认值
  • 若要仅为给定cmdlet或高级函数打开调试输出,请使用-Debug公共参数。
    • 警告 *:在 * Windows PowerShell * 中(但不再是PowerShell [Core] v6+),这将为遇到的每个Write-Debug语句呈现交互式调试提示。

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

$DebugPreference默认为SilentlyContinue,这解释了为什么默认情况下看不到Write-Debug语句的任何输出。
当使用**公共参数-Debug**时,实际上只为被调用的命令 * 设置$DebugPreference *,并且:

  • Windows PowerShell中,您*总是 * 将其设置为值Inquire,这不仅 * 打印 * Write-Debug消息,而且还会在每个此类语句处 * 暂停 * 以询问您希望如何继续
  • PowerShell [Core] v6 +中,该值现在(更明智地)设置为Continue
  • 对于支持-Debug公共参数的自定义脚本或函数,它必须是advanced,并使用param()块的[CmdletBinding()]属性声明,如Mathias' answer所示。
    • 由于在 * Windows PowerShell * 中,这种在每次-Write-Debug-调用时提示的行为可能是 * 破坏性的 *,$DebugPreference = 'Continue'可能是更好的方法。**如上所述,在PowerShell [Core] v6+中,这不再是一个问题。

注意:如果在高级函数或脚本中,您希望区分调用者将$DebugPreference设置为 * 首选项变量 * 与* 公共参数 * -Debug已传入(翻译为函数/脚本本地$DebugPreference变量),使用$PSBoundParameters.ContainsKey('Debug'); $true表示使用了-Debug
参考官方文件:https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.utility/write-debug
默认情况下,调试消息不显示在控制台中,但您可以使用Debug参数或$DebugPreference变量来显示它们。

bbuxkriu

bbuxkriu2#

如果您希望支持公共参数(包括-Debug),则需要在脚本中添加CmdletBinding属性:

[CmdletBinding()]
param()

Write-Debug Start
Write-Debug End

我建议查看about_Functions_CmdletBindingAttribute帮助文件

r9f1avp5

r9f1avp53#

如果将$DebugPreference = 'Continue'放在每个模块函数的进程块中,它将按预期工作。有一点重复,但这比其他一些建议的解决方案要容易得多。

相关问题