Set-PSDebug -Trace n
的输出到文件。(File 是
此处为关键字。)示例:
脚本B:
Set-PSDebug -Trace 1
Function FuncA {
Write-Host "ABC"
FuncB
}
Function FuncB {
Write-Host "123"
}
FuncA
FuncB
正确的调试输出是:
DEBUG: 15+ >>>> FuncA
DEBUG: 6+ Function FuncA >>>> {
DEBUG: 7+ >>>> Write-Host "ABC"
ABC
DEBUG: 8+ >>>> FuncB
DEBUG: 11+ Function FuncB >>>> {
DEBUG: 12+ >>>> Write-Host "123"
123
DEBUG: 13+ >>>> }
DEBUG: 9+ >>>> }
DEBUG: 16+ >>>> FuncB
DEBUG: 11+ Function FuncB >>>> {
DEBUG: 12+ >>>> Write-Host "123"
123
DEBUG: 13+ >>>> }
.
但是当我现在尝试通过启动进程从脚本
A运行它以将输出捕获到文件中时:
$SParguments = "-NoProfile -file `"$stdTracefile`""
Start-Process 'C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe' -ArgumentList $SParguments -RedirectStandardOutput $stdTracelog
输出奇怪的是这样的:
DEBUG: 15+ >>>> FuncA
DEBUG: 6+ Function FuncA >>>> {
DEBUG: 7+ >>>> Write-Host "ABC"
ABC
123
123
尽管脚本正确完成,但调试消息在第一个函数之后停止。
有什么想法以及如何规避或避免这种情况吗?
或者,我正在寻找另一种解决方案来实现顶部所述的两个目标。
顺便说一句:我也尝试过使用trace-command
,它有一个
filepath
参数,但我不知道如何跟踪整个脚本,而且我不知道如何获取Set-PSDebug提供的信息:正在执行的行和正在执行的命令,没有其余的。 我想自动处理调试输出,而 Set-PSDebug 的输出正是我所需要的。
使用
Write-
any 似乎会从遇到第一个 cmdlet 时中断 PSDebug 输出。注释掉它们,例如Write-Host "ABC"
线将允许看到更多跟踪,直到调用 FuncB 中的
Write-Host
。使用
return
Write-Host
"ABC"
和
"123"
部分。我不喜欢从函数中吐出这样的文本,但至少它给出了我们在这个示例中所期望的内容。见下文。在脚本 A 末尾留一个空行会改变输出的行为,即,如果第 13 行末尾有回车符,则输出格式如下所示。如果没有,那么您最终会在同一行上得到两行调试:
解决方案
C:\Scripts\PowerShell\Test-Debug.ps1
Set-PSDebug -Trace 1
Function FuncA {
"ABC"
FuncB
}
Function FuncB {
"123"
}
FuncA
FuncB
脚本 B: :
C:\Scripts\PowerShell\Call-TestDebug.ps1
$stdTraceFile = "C:\Scripts\PowerShell\Test-Debug.ps1"
$stdTraceLog = Join-Path $env:TEMP test.log
$PSExecutable = 'C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe'
$SParguments = "-Version 4 -NoProfile -File $stdTracefile"
Start-Process -FilePath $PSExecutable -ArgumentList $SParguments `
-RedirectStandardOutput $stdTracelog
test.log中期望的输出:
DEBUG: 12+ >>>> FuncA
DEBUG: 3+ Function FuncA >>>> {
DEBUG: 4+ >>>> "ABC"
ABC
DEBUG: 5+ >>>> FuncB
DEBUG: 8+ Function FuncB >>>> {
DEBUG: 9+ >>>> "123"
123
DEBUG: 10+ >>>> }
DEBUG: 6+ >>>> }
DEBUG: 13+ >>>> FuncB
DEBUG: 8+ Function FuncB >>>> {
DEBUG: 9+ >>>> "123"
123
DEBUG: 10+ >>>> }
如果您无法修改当前正在调用
Write-Host
模块