2011-09-22 24 views

回答

18

只是做的另一种方式......可以是一个小比SQLPS更快得到快速答案。


(get-itemproperty 'HKLM:\SOFTWARE\Microsoft\Microsoft SQL Server').InstalledInstances 
+0

+1我的电脑上的最佳性能! –

2
$a = "MyComputerName" 

[System.Data.Sql.SqlDataSourceEnumerator]::Instance.GetDataSources() | ? { $_.servername -eq $a} 

亚伦方法返回一个更确定的响应。 阅读Here约Instance.GetDataSources()

3

进口PowerShell中的SQL Server扩展:

Import-Module SqlServer 

然后执行这些命令

Set-Location SQLSERVER:\SQL\localhost 
Get-ChildItem 
+0

在我的电脑上,从SQLSERVER获取子项:\ SQL \ localhost真的很慢。我现在无法在其他电脑上测试。是一种正常的行为?谢谢 –

+0

更好的方法是:get-childitem |选择实例名称 –

3
[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.SqlWmiManagement") | out-null 
$mach = '.' 
$m = New-Object ('Microsoft.SqlServer.Management.Smo.Wmi.ManagedComputer') $mach 
$m.ServerInstances 
+0

也可以使用'$ m =(Get-Item SQLServer:\ SQL \ $ mach).ManagedComputer' –

4

我发现(至少对我来说)以上都不回我的SQL Express实例。我有5个命名实例,4个全脂SQL Server,1个SQL Express。上面的答案中包含了4种全脂肪,但SQL Express并不包含在内。所以我在互联网上做了一点小小的探索,James Kehr发现了this article,它列出了一台机器上所有SQL Server实例的信息。我用这个代码作为编写下面的函数的基础。

# get all sql instances, defaults to local machine, '.' 
Function Get-SqlInstances { 
    Param($ServerName = '.') 

    $localInstances = @() 
    [array]$captions = gwmi win32_service -computerName $ServerName | ?{$_.Name -match "mssql*" -and $_.PathName -match "sqlservr.exe"} | %{$_.Caption} 
    foreach ($caption in $captions) { 
    if ($caption -eq "MSSQLSERVER") { 
     $localInstances += "MSSQLSERVER" 
    } else { 
     $temp = $caption | %{$_.split(" ")[-1]} | %{$_.trimStart("(")} | %{$_.trimEnd(")")} 
     $localInstances += "$ServerName\$temp" 
    } 
    } 
    $localInstances 
} 
0

的System.Data.Sql命名空间包含支持SQL Server特定的功能的类。

通过使用System.Data.Sql命名空间,你可以在Windows的电源外壳使用此命令获取计算机上的所有MSSQL实例: [System.Data.Sql.SqlDataSourceEnumerator]::Instance.GetDataSources()

相关问题