我正在尝试按顺序运行sql查询。如果任何一个sql查询失败,那么windows powershell脚本应该退出并发送电子邮件。应将日志写入日志目录。其中data =<这将在运行时>
中传递以下示例代码:
Invoke-Sqlcmd -Query "SELECT data from emp where data=<run time argument>;" -ServerInstance "MyComputer\MyInstance"
Invoke-Sqlcmd -Query "SELECT data from class where data=<run time argument>;" -ServerInstance "MyComputer\MyInstance"
Invoke-Sqlcmd -Query "SELECT data from stud where data=<run time argument>;" -ServerInstance "MyComputer\MyInstance"
Invoke-Sqlcmd -Query "SELECT data from cust where data=<run time argument>;" -ServerInstance "MyComputer\MyInstance"
Invoke-Sqlcmd -Query "SELECT data from new where data=<run time argument>;" -ServerInstance "MyComputer\MyInstance"
任何帮助都将不胜感激。
此致
答案 0 :(得分:0)
当&#34; sql查询失败时它会是什么样子&#34;?你可以依赖于Invoke-SqlCmd函数的返回,或者有一个预期的&#34;失败&#34;消息(或多条消息)。
我不熟悉Invoke-SqlCmd。查看the MSDN page; -AbortOnError
看起来像-ErrorLevel
一样对你有帮助。
以下是单个预期错误的大纲,并对如何扩展进行了评论。值得将您的查询存储在一个数组中,以便您可以循环然后跳出循环而不是使用线性代码(必须在每个invoke-sqlcmd
之后复制并粘贴检查部分
# string with a single error. you could use an array and add
# a foreach ($error in $errors) on the line marked #here
$expectedError = "Failed"
# Functions have to appear above where they are used
Function Check-SQLResults($result){
# a try-catch statement will execute the code in the try part, going
# to the catach part on a TERMINATING error
try{
# check each line for your expected error
foreach($line in $result){
#here
if($line -like "*$expectedError*"){
Write-Error "Something went wrong: $line" -ErrorAction Stop
}
}
# true is only returned if none of the result lines are like your error
return $true
}catch{
# false is returned if any lines contain error
return $false
}
}
# store the sql outcome in a variable so you can check it
$result = Invoke-Sqlcmd -Query "SELECT data from emp where data=;" -ServerInstance "MyComputer\MyInstance"
# using a function that tells you if the results contain an error or not is neater.
# again, this is manually dealing with errors and invoke-sqlcmd provides other options.
$resultIsErrorFree = Check-SQLResults -result $result
If(resultIsErrorFree -eq $true){
# execute next invoke-sqlcmd
}else{
# Send e-mail. $results can be added to body.
}