无法获得PowerShell来处理SQL Server连接失败

时间:2012-10-25 15:38:49

标签: sql-server sql-server-2008 powershell smo

我故意尝试登录到我没有登录的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;
} ; 

1 个答案:

答案 0 :(得分:1)

我找到了解决方法。微软已经证实这是SMO中的一个错误,他们认为现在还不足以解决这个问题。解决方法详述如下:

https://connect.microsoft.com/SQLServer/feedback/details/636401/smo-is-inconsistent-when-raising-errors-for-login-faliures#