我正在学习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
但同样,输出不会写入控制台。显然,我错误地使用了写调试。我如何获得调试输出以写入控制台?
3条答案
按热度按时间whlutmcx1#
$DebugPreference = 'Continue'
开始查看Write-Debug
调用的输出。$DebugPreference = 'SilentlyContinue'
将首选项变量$DebugPreference
恢复为其默认值-Debug
公共参数。Write-Debug
语句呈现交互式调试提示。是否打印
Write-Debug
语句的输出由两种机制控制:$DebugPreference
首选项变量**的值-参见Get-Help about_Preference_Variables
。-Debug
公共参数**调用cmdlet或 * advanced * 脚本/函数(覆盖$DebugPreference
值)时,特殊、命令范围-请参阅Get-Help about_CommonParameters
。$DebugPreference
默认为SilentlyContinue
,这解释了为什么默认情况下看不到Write-Debug
语句的任何输出。当使用**公共参数
-Debug
**时,实际上只为被调用的命令 * 设置$DebugPreference
*,并且:Inquire
,这不仅 * 打印 *Write-Debug
消息,而且还会在每个此类语句处 * 暂停 * 以询问您希望如何继续。Continue
。-Debug
公共参数的自定义脚本或函数,它必须是advanced,并使用param()
块的[CmdletBinding()]
属性声明,如Mathias' answer所示。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变量来显示它们。
bbuxkriu2#
如果您希望支持公共参数(包括
-Debug
),则需要在脚本中添加CmdletBinding
属性:我建议查看
about_Functions_CmdletBindingAttribute
帮助文件r9f1avp53#
如果将
$DebugPreference = 'Continue'
放在每个模块函数的进程块中,它将按预期工作。有一点重复,但这比其他一些建议的解决方案要容易得多。