如何将 PowerShell 控制台中打印的 (Python) 错误消息定向到文本文件

如何将 PowerShell 控制台中打印的 (Python) 错误消息定向到文本文件

首先,我感兴趣的重定向错误不是 PowerShell 错误,而是由我的 PowerShell 脚本中调用的 Python 脚本生成的错误。我已阅读此处(以及其他 StackExchange 网站、Windows PowerShell 脚本编写人员文章和其他各个位置)的多篇文章。这导致我开发了如下所示的脚本,但输出有些奇怪。

$ErrorActionPreference="SilentlyContinue"
Stop-Transcript | out-null
$ErrorActionPreference = "Continue"

$SnapsToTest = Get-ChildItem C:\Snaps\ -Directory
$ErrorFile = "C:\Tools\Scripts\Errors.txt"
$SnapDir = "C:\Logs"
$LogDir = "\var\log\"
$LogFile = "support.log"
$env:PYTHONIOENCODING="UTF-8"

Start-Transcript -path $ErrorFile
Push-Location
Set-Location -Path $SnapDir

$SnapsToTest | ForEach-Object {
        Write-Host $_.Name
        python C:\Tools\Scripts\script1.py $_.Name
        $LogToTest = $_.Name+$LogDir+$LogFile
        python C:\Tools\Scripts\script2.py $LogToTest
    }

Pop-Location
Stop-Transcript

现在,如果我运行脚本,.\myscript.ps1 > output.text我几乎可以得到我想要的结果,但不完全是。

我最终得到了两个文件,output.texterrors.txt

输出文本显示 Python 脚本生成的所有输出。错误文本文件显示写入屏幕的部分输出,但如果 Python 脚本崩溃并写出其堆栈跟踪,则不会显示,但是我确实在终端中看到了这一点,我不明白这一点。

例如,我在错误文本文件中看到的输出是:

**********************
Windows PowerShell transcript start
Start time: 20160429160228
Username: PC\me
RunAs User: PC\me
Machine: PC(Microsoft Windows NT 10.0.14328.0)
Host Application: C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe
Process ID: 16844
PSVersion: 5.1.14328.1000
PSEdition: Desktop
PSCompatibleVersions: 1.0, 2.0, 3.0, 4.0, 5.0, 5.1.14328.1000
CLRVersion: 4.0.30319.42000
BuildVersion: 10.0.14328.1000
WSManStackVersion: 3.0
PSRemotingProtocolVersion: 2.3
SerializationVersion: 1.1.0.1
**********************
SnapDir1
SnapDir2
SnapDir3

但是,我在控制台中看到的是:

C:\Tools\Scripts> .\myscript.ps1 | Out-File output.txt
SnapDir1
SnapDir2
Traceback (most recent call last):
  File "C:\Tools\Scripts\script1.py", line 446, in <module>
    main(sys.argv[1])
  File "C:\Tools\Scripts\script1.py", line 436, in main
    dba = DBAnalyser(rootdir)
  File "C:\Tools\Scripts\script1.py", line 54, in __init__
    self.osstatus = self._read_osstatus(osstatus_file)
  File "C:\Tools\Scripts\script1.py", line 170, in _read_osstatus
    ret[hostname]["meminfo"] = { "memtotal": memtotal, "memfree": memfree}
UnboundLocalError: local variable 'memtotal' referenced before assignment
SnapDir3

我不知道如何让 PowerShell 控制台中看到的上述错误显示在 Errors.txt 文件中

这是在 Windows 10 Pro 64 位中运行的。

相关内容