如果任何SQL脚本通过Powershell执行错误,则sqlcmd函数不会引发错误消息

时间:2019-05-13 03:54:53

标签: sql-server powershell automation

在PowerShell脚本上使用Sqlcmd函数执行多个SQL脚本,以将结果作为smss输出,但是通过sqlcmd,如果任何SQL脚本有错误,它不会抛出错误消息或无法编写catch方法,请指导我如果任何脚本有错误,可以捕获错误。

使用Invoke-Sqlcmd命令,我无法捕获执行任何更新或插入语句(如“ 1行受影响”)后SSMS给出的脚本执行输出,因此我需要使用sqlcmd命令来执行sql脚本和现在捕获了所有脚本记录,但是在Invoke-sqlcmd命令上,如果sql脚本中有任何错误,它将转到catch块并显示错误,但是当我使用SQLCMD时,如果SQL脚本中有任何错误,它将不会被捕获在try块中阻止它的状态并继续。

因此,现在请帮助我如何捕获和移动它以捕获块,或者像使用Invoke-SQLCMD命令之前所做的那样捕获错误。

这是此链接的延续: Not getting ouput after successful execution of the SQL scripts through powershell

这是我的代码块,不会捕获块:

尝试                     {

                  #$result = "Sqlcmd.exe -S $InstanceNAme -d $dbname -Q ""Insert into [DUR2_A].[dbo].[emp_info] values(1,'Ram','Kolkata')"""
                  #Invoke-Expression $result | Out-File filesystem::$ScriptOutPutpath$scriptfilesc$out
                  sqlcmd -S $InstanceNAme -i $scriptfiles1 -o $ScriptOutPutpath$scriptfilesc$out -m1
                  Move-Item filesystem::$scriptfiles1 filesystem::$Scriptbackuppath


                }
                catch
                {


                     $ErrorMessage = $_.Exception.Message
                     $FailedItem = $_.Exception.ItemName
                     echo "Error for $scriptfilesc - $($_.Exception.Message)" | Out-File filesystem::$error_log$scriptfilesc$errorout
                     Send-MailMessage -from test@test.com -To IO-SD.GP.test@test.com -SmtpServer mailrelay.test.com -Subject "DUR Error" -Body "Script $scriptfilesc has not been executed becasue of Error Message $ErrorMessage.Kindly check the attachd script and error message" -Attachments filesystem::$error_log$scriptfilesc$errorout,filesystem::$scriptfiles1
                     Move-Item filesystem::$scriptfiles1 filesystem::$Scriptbackuppath


                }

0 个答案:

没有答案