2013-06-19 184 views
0

我有一個從數據庫(MS SQL 2008)讀取計算機信息行並將其存儲到讀取器中的PowerShell。如何處理交易異常

# Open the database connection 
$conn.Open() 

# Create and execute the SQL Query 

$cmd = New-Object System.Data.SqlClient.SqlCommand($sql,$conn) 

$rdr = $cmd.ExecuteReader() 

# Read Computer Information into multidimensional array 
$count=0 
while ($rdr.read()){ 
    $sql_output += ,@($rdr.GetValue(0), $rdr.GetValue(1), $rdr.GetValue(2), 
    $rdr.GetValue(3)) 
    $count=$count + 1 
} 


# Close the database connection 
$conn.Close()  

Write-host Finished reading $count IP addresses from database 

約50%的時間,我得到一個異常

異常調用 「讀」 和 「0」 的參數(一個或多個):「事務(進程 ID 107)中的上鎖定僵持資源與另一個進程,並已被選爲死鎖受害者,重新運行交易。「在 C:\ script.ps1:83字符:17 +而($ rdr.read < < < <()){ + CategoryInfo:NotSpecified:(:) [],MethodInvocationException + FullyQualifiedErrorId:DotNetMethodException

我在數據庫中有大約18,000臺計算機。當拋出這個異常時,它只能讀取10,000個,它隨時間變化。

如何處理異常,以便它讀取所有18,000臺計算機?

回答

1

嘗試包裹在try..catch塊的執行和循環是這樣的:

$conn.Open() 
$cmd = New-Object System.Data.SqlClient.SqlCommand($sql,$conn) 

do { try { 
    $rdr = $cmd.ExecuteReader() 

    $count=0 
    while ($rdr.read()) { 
     $sql_output += ,@($rdr.GetValue(0), $rdr.GetValue(1), $rdr.GetValue(2), 
         $rdr.GetValue(3)) 
     $count=$count + 1 
    } 

    $transactionComplete = $true } catch { $transactionComplete = $false } } until ($transactionComplete) 

$conn.Close()

然而,更好的方法是識別和避免死鎖狀態(如果可能)。

+0

會試試這個 - 謝謝 – Rhonda

+0

不客氣。如果您發現它能解決您的問題,請考慮[接受答案](http://meta.stackexchange.com/a/5235)。 –