0

我们正在使用Start-TranscriptStop-Transcript记录 PowerShell 脚本的输出。

该脚本正在执行应用程序的安装,因此$ErrorActionPreference = "Stop"如果遇到任何错误,我们也会停止执行。

这样做的问题是,如果发生错误,脚本会在错误输出到控制台之前停止。这意味着错误不会包含在我们的日志文件中。即使我们使用try...finally如下方式也是如此:

Start-Transcript "$(Split-Path $MyInvocation.MyCommand.Path -Leaf)-$((Get-Date).toUniversalTime().ToString('yyyy-MM-ddTHH-mm-ss')).log"

$ErrorActionPreference = "Stop"

try
{
    Write-Host "various things happening"

    Write-Error "an error"
}
finally
{
    Stop-Transcript
}

运行此脚本的控制台输出为:

E:\> .\Testing.ps1
Transcript started, output file is Testing.ps1-2013-02-18T11-39-27.log
various things happening
Transcript stopped, output file is ...
Write-Error : an error
At ...

我们可以做些什么来确保错误消息包含在日志中?

4

2 回答 2

1

也许这可以工作:

Start-Transcript "$(Split-Path $MyInvocation.MyCommand.Path -Leaf)-$((Get-Date).toUniversalTime().ToString('yyyy-MM-ddTHH-mm-ss')).log"    
$ErrorActionPreference = "Stop"
try
{    
  write-host " A million stuff to do..."    
  $a = 1/0    
}

catch [system.exception]
{
   Write-host "Exception String: "+ $($_.Exception.Message)
   Stop-Transcript
} 
 try{
  stop-transcript
}
catch [System.InvalidOperationException]{}
于 2013-02-18T12:13:42.490 回答
0

我们为此找到了以下解决方案,如下所示:

Start-Transcript "$(Split-Path $MyInvocation.MyCommand.Path -Leaf)-$((Get-Date).toUniversalTime().ToString('yyyy-MM-ddTHH-mm-ss')).log"

$ErrorActionPreference = "Stop"

trap {
    Write-Error $error[0] -ErrorAction Continue
    Stop-Transcript
    exit 1
}

Write-Host "various things happening"
Write-Error "an error"

Stop-Transcript
于 2013-02-18T12:14:05.330 回答