如果有任何错误,我想捕获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
}
答案 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的参数。