Powershell捕获SQL错误并重定向到日志文件

时间:2016-01-10 04:55:58

标签: powershell

我试试,在我的powershell中捕获语句来处理错误异常,但是下面的语句没有输出sql错误消息到.log文件。

Try{

Invoke-SqlCmd -InputFile "D:\DropBoxFolder\Dropbox\Public\WIKI_POWERSHELL\AdminTask\ExecutePowerShell_From_BAT\Map_AU.sql"
   }

Catch{
$ErrorMessage = $_.Exception.Message
$Time=Get-Date
"This script failed at $Time and error message was $ErrorMessage" | out-file D:\DropBoxFolder\Dropbox\Public\WIKI_POWERSHELL\AdminTask\ExecutePowerShell_From_BAT\Inovke_SQLScript.log -append
   }

Finally{

$Time=Get-Date
"This script made a read attempt at $Time" | out-file D:\DropBoxFolder\Dropbox\Public\WIKI_POWERSHELL\AdminTask\ExecutePowerShell_From_BAT\Inovke_SQLScript.log -append

$con.Close()
   }

这里从powershell返回错误,我想将错误重定向到.log

Invoke-Sqlcmd:已经有一个名为' Map_AU234'在数据库中。 在D:\ DropBoxFolder \ Dropbox \ Public \ WIKI_POWERSHELL \ AdminTask \ ExecutePowerShell_ From_BAT \ Inovke_SQLScript.ps1:49 char:14 + Invoke-SqlCmd<<<< -InputFile" D:\ DropBoxFolder \ Dropbox \ Public \ WIKI_POWERSHE LL \的AdminTask \ ExecutePowerShell_From_BAT \ Map_AU.sql"     + CategoryInfo:InvalidOperation :( :) [Invoke-Sqlcmd],SqlPowerS    hellSqlExecutionException     + FullyQualifiedErrorId:SqlError,Microsoft.SqlServer.Management.PowerShe    ll.GetScriptCommand

1 个答案:

答案 0 :(得分:0)

在Invoke-SqlCmd

结束时添加-ErrorAction Stop后,它可以正常工作