2017-02-21 47 views
0

我試圖按順序運行sql查詢。如果任何一個sql查詢失敗,那麼Windows PowerShell腳本應該退出併發送電子郵件。該日誌應該寫入日誌目錄。其中數據= <這將在運行時間低於>使用PowerShell依次運行運行時參數調用多個sql

示例代碼傳遞:

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" 

任何幫助,將不勝感激。

Regards,

+1

後複製並粘貼檢查部到目前爲止,您是否收集了需要彙總的不同部分的任何信息(SQL,電子郵件,寫入文件)? – TechSpud

+0

腳本必須按順序執行sql查詢。將sql查詢的輸出存儲在文件命名中,如file1 ,file2等。在運行時會傳入where條件輸入。 – user4432340

回答

0

當「sql查詢失敗」時它看起來像什麼?你可以依賴Invoke-SqlCmd函數的返回,或者有一個預期的「失敗」消息(或多個消息)。我並不熟悉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. 
} 
+0

非常感謝。我對powershell很新。'$ SqlQuery =「select * from emp where data = 」 try { $ SqlResourceMon = Invoke-SqlCmd -Query $ SqlQuery -ServerInstance「SQLINSTANCENAME」 - 數據庫「temp」-ErrorAction停止-verbose 4>&1 | OUTFILE someoutfile.txt } 抓 { $ _ 發送- - 摘自MAILMESSAGE 「X」 - 要 「Y」 -subject 「測試電子郵件」 - 身體 「TEST」 「錯誤運行SQL $ SqlQuery類」 }'請檢查這是否會起作用。 – user4432340

+0

歡迎來到StackOverflow,歡迎來到PowerShell! MSDN和文檔是你最好的朋友。代碼看起來很好,據我所知,你有沒有試過運行它?我無法爲你運行它。 – gms0ulman