Pergunta

We're using Start-Transcript and Stop-Transcript to log the output from our PowerShell script.

The script is performing an installation of an application, so we're also using $ErrorActionPreference = "Stop" to cease execution if we encounter any errors.

The problem with this is that if an error happens, the transcript gets stopped before the error is output to the console. This means that the error does not get included in our log file. This holds true even if we use try...finally as follows:

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
}

The console output from running this script is:

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 ...

What can we do to ensure that the error message gets included in the log?

Foi útil?

Solução 2

We found the following solution for this, as follows:

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

Outras dicas

Maybe this can works:

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]{}
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top