![](/img/trans.png)
[英]How can I handle lost client connection in a SQL Server T-SQL try-catch block?
[英]Can't get powershell to handle a SQL Server connection failure
我故意嘗試登錄到我沒有登錄的SQL Server,以使用SQL Server 2008 R2測試PowerShell 2.0和SMO的錯誤處理。
這是我的腳本:
param ([String]$instanceName);
[System.Reflection.Assembly]::LoadWithPartialName('Microsoft.SqlServer.SMO') | out-null;
$conn = new-object Microsoft.SqlServer.Management.Common.ServerConnection ;
$conn.LoginSecure = $true;
$conn.ServerInstance = $instanceName ;
$conn.NonPooledConnection = $true ;
try {
$serverInstance = New-Object Microsoft.SqlServer.Management.Smo.Server ($conn) ;
}
catch {
$err = $Error[0].Exception ;
write-host "Error caught: " $err.Message ;
continue ;
} ;
Write-Output $serverInstance.Version;
catch塊沒有被執行。 有任何想法嗎? 我也嘗試使用trap
功能捕獲它,但得到了相同的結果。
更新1
我已將我的腳本更改為以下內容並讓它在線捕獲異常
foreach($j in $serverInstance.Databases) {
如果我注釋掉foreach循環,foreach循環下面的行不會引發異常 ,盡管它應該(IMO)。
param ([String]$instanceName);
[System.Reflection.Assembly]::LoadWithPartialName('Microsoft.SqlServer.SMO') | out-null; # load the SMO assembly
clear
$ErrorActionPreference = "Stop";
$conn = new-object Microsoft.SqlServer.Management.Common.ServerConnection ;
$conn.LoginSecure = $false;
$conn.Login = "sa" ;
$conn.Password = "password" ;
$conn.ServerInstance = $instanceName ;
$conn.NonPooledConnection = $true ;
try {
$serverInstance = New-Object Microsoft.SqlServer.Management.Smo.Server ($conn) ;
foreach($j in $serverInstance.Databases) {
write-host $j.name ;
} ;
Write-Output $serverInstance.Databases.Count;
}
catch [Microsoft.SqlServer.Management.Common.ConnectionFailureException] {
$err = $Error[0].Exception ;
write-host "Error caught: " $err.Message ;
while ( $err.InnerException ) {
$err = $err.InnerException;
Write-Host "Inner exception:" $err.InnerException.Message;
};
return;
} ;
我找到了一個解決方法。 微軟已經證實這是SMO中的一個錯誤,他們認為現在還不足以解決這個問題。 解決方法詳述如下:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.