PowerShell: Get list of registered SQL Servers

No reason to maintain more than one list of SQL Servers when you can query SSMS’s Registered Servers.


Import-Module SQLPS -DisableNameChecking 
$SQLInstanceProd = @()
            
$ServerGroup = 'PRODUCTION'
$SQLPath = "SQLSERVER:\sqlregistration\Database Engine Server Group\PROD*\" 
        
$SQLInstanceProd += @(get-childitem $SQLPath -Recurse).Name | ?{$_ -notmatch '\d\d\d\d'} | % {
    $MyPSObject = New-Object PSObject -Property @{ 
            SQLInstance  = $_ 
            ServerGroup  = $ServerGroup;
        }
    $MyPSObject
    }

$SQLInstanceProd

Putting that logic into Get-RegisteredServers I populate the following list in my Profile.

$AllServersList = (Get-RegisteredServers).SQLInstance
$AllComputersList = $AllServersList | %{  $_.split('\')[0] }
$SQLInstanceDev = $((Get-RegisteredServers) |Where-Object {$_.ServerGroup -match 'DEV'}).SQLInstance
$SQLInstanceTest = $((Get-RegisteredServers) |Where-Object {$_.ServerGroup -match 'TEST'}).SQLInstance
$SQLInstanceProd = $((Get-RegisteredServers) |Where-Object {$_.ServerGroup -match 'PROD'}).SQLInstance

Comments are closed.

Post Navigation