PowerShell 2,3,x 具有尝试将 PowerShell 窗口的所有输出记录到文本文件的Transcript cmdlet 。有一些限制。
这是演示这一点的示例代码:
$this_path = Split-Path -Path $MyInvocation.MyCommand.Path -Parent
$log_path = Join-Path -Path $this_path -ChildPath script_log.txt
Start-Transcript -Path $log_path
$VerbosePreference = "continue"
$ErrorActionPreference = "continue"
$DebugPreference = "continue"
$WarningPreference = "continue"
& hostname.exe
Write-Host "write-host"
Write-Verbose "write-verbose"
Write-Error "write-error"
Write-Debug "write-debug"
Write-Warning "write-warning"
Get-Date
Stop-Transcript
& notepad $log_path
上面的所有内容都将在 script_log.txt 中捕获,除了输出之外,hostname.exe
因为它是一个外部可执行文件。
有一些解决方法:
powershell.exe -noprofile -file script.ps1 > script.log
这会捕获包括hostname.exe
' 的输出在内的所有内容,但它是在脚本之外完成的。
另一个是对于每个外部命令,通过主机 API 管道输出:
& hostname.exe | Out-Default
这是在脚本中完成的,但是您会丢失 shell 窗口上 exe 中的任何文本着色。