Sql server Can';无法让powershell处理SQL Server连接故障
我故意尝试登录到一个SQL Server,在那里我没有登录名来测试使用PowerShell 2.0和SMO使用SQL Server 2008 R2进行的一些错误处理 这是我的剧本:Sql server Can';无法让powershell处理SQL Server连接故障,sql-server,sql-server-2008,powershell,smo,Sql Server,Sql Server 2008,Powershell,Smo,我故意尝试登录到一个SQL Server,在那里我没有登录名来测试使用PowerShell 2.0和SMO使用SQL Server 2008 R2进行的一些错误处理 这是我的剧本: param ([String]$instanceName); [System.Reflection.Assembly]::LoadWithPartialName('Microsoft.SqlServer.SMO') | out-null; $conn = new-object Microsoft.SqlServer
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)
我找到了一个解决办法。微软已经确认这是SMO中的一个bug,他们认为现在修复这个bug还不够重要。此处详细介绍了解决方法:
SMO和
try
块中的任何内容实际上都没有连接到服务器。将Write Output
命令移动到try
块是否会导致错误?@Pondlife将$serverInstance.Version
移动到try
块不会导致错误。我也有同样的行为。我在标题“更新1”下的问题中添加了一个更新的脚本。Microsoft Connect已失效,链接不再工作
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;
} ;