由invoke-sqlcmd引发的Catch异常

时间:2016-02-27 07:30:06

标签: powershell

如果有任何错误,我想捕获invoke-sqlcmd。但是当我运行以下命令时,如果invoke-sqlcmd无效,则无法捕获它。如何捕捉这个例外?

Invoke-SqlCmd -InputFile "D:\Tables\Script_CreateTable.tab"
}

Catch{
$ErrorMessage = $_.Exception.Message
$Time=Get-Date
"This script failed at $Time and error message was $ErrorMessage" | out-file D:\Log\CreateTable.log -append
}

Finally{

$Time=Get-Date
"This script made a read attempt at $Time" | out-file D:\Log   \CreateTable.log -append
 }

1 个答案:

答案 0 :(得分:0)

我无法测试这个,但我猜这个错误不是终端异常。解决方法是在命令末尾添加-ErrorAction Stop。尝试:

try {
    Invoke-SqlCmd -InputFile "D:\Tables\Script_CreateTable.tab" -ErrorAction Stop
}
Catch{
    $ErrorMessage = $_.Exception.Message
    $Time=Get-Date
    "This script failed at $Time and error message was $ErrorMessage" | out-file D:\Log\CreateTable.log -append
}

-AbortOnError,它似乎是Invoke-Sqlcmd的特定于cmdlet的参数。

相关问题