可以将Write-debug消息传输到Log文件吗?

Sam*_*abu 1 powershell powershell-2.0

Write-verbose消息不会重定向到Out-File.

我的高级功能失败,没有任何痕迹,所以我想放置调试消息.当脚本执行时,它将无法在控制台中运行,因此我看不到该消息.

如果消息可以传输到日志文件,那么我可以看到它.Write-debug是否可以将值传递给日志文件?

mca*_*ing 7

如果您使用的是Powershell v3 +,则可以将调试流重定向到文本文件:

示例文件:test.ps1

$debugPreference = "Continue"
Write-Output "Output msg"
Write-Debug "Debug msg"
Run Code Online (Sandbox Code Playgroud)

从powershell命令行:

c:\temp\test.ps1 5>c:\debug.txt
Run Code Online (Sandbox Code Playgroud)

c:\ debug.txt然后显示单行"Debug msg"

5> c:\ debug.txt有点模糊,所以让我们分解它."5"表示调试流,这是此处此处描述的第五个内在Powershell流.> c:\ debug.txt然后告诉它将所有调试输出重定向到该文件.

您还可以使用5>&1,将调试流重定向到普通标准输出.

如果您在Powershell v2中,您可以查看这个提供良好日志记录的编译模块,或者您可以使用类似于此处所述的脚本本地函数:

$DebuglogPreference = 'Continue'
function Write-DebugLog 
{
   param( [string]$message, [string]$filepath = 'c:\debug.txt' )

   if ($DebuglogPreference -eq 'Continue') 
   {
       $message | Out-File $filepath -append
   }
}

Write-DebugLog "Debug msg"
Run Code Online (Sandbox Code Playgroud)