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