2012-10-25 42 views
3

我故意嘗試登錄到沒有登錄的SQL Server,以使用SQL Server 2008 R2測試PowerShell 2.0和SMO的某些錯誤處理。無法獲取PowerShell來處理SQL Server連接失敗

這裏是我的腳本:

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; 
} ; 
+1

SMO [打開需要時連接在你的'try'(http://msdn.microsoft.com/en-us/library/ms162132.aspx)並沒有什麼塊實際上連接到服務器。將'Write-Output'命令移動到'try'塊是否會導致錯誤? – Pondlife

+0

@Pondlife將'$ serverInstance.Version'移動到'try'塊不會導致錯誤。我得到了同樣的行爲。 –

+0

我在標題UPDATE 1下爲我的問題添加了更新的腳本。 –

回答