Powershell毫无例外地跳进了最后的消息

时间:2012-08-10 13:14:36

标签: powershell exception-handling try-catch-finally

我的PowerShell代码有问题。有时 - 无论出于何种原因 - 我的脚本会直接跳转到finally块,而不会发出来自catch块的任何错误消息。这是我的PowerShell代码:

try
{
    $sleepTime = $reservationDuration - $prepareTime
    (get-date -format hh:mm:ss)+"`tinfo:`tstart sleep before warning VIP sleep-time:"+$sleepTime | out-file $logFilePath -append
    start-sleep -s $sleepTime
    (get-date -format hh:mm:ss)+"`tinfo:`tsleeptime over" | out-file $logFilePath -append
}
catch
{
    (get-date -format hh:mm:ss)+"`terror:`tchaught exception: "+$error[0] | out-file $logFilePath -append
}


finally{
    (get-date -format hh:mm:ss)+"`tinfo:`tFinally" | out-file $logFilePath -append
}

如您所见,我正在编写一些日志文件以查看发生了什么。我总是在$ sleepTime变量中得到正确的int值。然而,有时它会直接进入finally块而不写“睡眠时间超过......”甚至“应对异常...”

1 个答案:

答案 0 :(得分:0)

catch块执行的唯一时间是try块中有异常。你在try块中做的唯一有可能产生异常的事情就是写入日志文件。

因此只有在存在阻止将输出写入日志文件的异常时才会执行catch块。

如果我遗失了任何东西,请告诉我。