$ ErrorActionPreference =“Stop”时按顺序执行finally块

时间:2013-02-18 11:42:12

标签: powershell-v2.0 try-finally

我们正在使用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 ...

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

2 个答案:

答案 0 :(得分: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]{}

答案 1 :(得分: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