PowerShell - Get All SQL Server Instances In Environment

ben himself's picture
cls
import-module failoverclusters
Import-Module -Name SQLPS -DisableNameChecking



$servers = "comma","separated","server","list"

foreach($server in $servers)
{
    try
    {
    <# Fail safe, set this to server name first to fall back on #>
    $virtual_name = $server;
    $instances = '';
    try{
    $virtual_name = ((get-clusterresource -Cluster $server -ErrorAction SilentlyContinue -WarningAction SilentlyContinue | 
                        get-clusterparameter VirtualServerName -ErrorAction SilentlyContinue -WarningAction SilentlyContinue | 
                        Select Value -ErrorAction SilentlyContinue -WarningAction SilentlyContinue)[0].Value ) 
    }
    catch{<#this was the only way to stop certain warnings.  No catch really needed.#>}
    
    $server = $virtual_name;
      
    $path = "SQLServer:\SQL\" + $server;
    $instances = Get-ChildItem -Path $path -ErrorAction SilentlyContinue -WarningAction SilentlyContinue;
    
    foreach($instance in $instances)
    {
        write-host $instance;    
    }
    }
    
    catch{<#this was the only way to stop certain warnings.  No catch really needed.#>}
    
}

Categories: