Get ServerNames from SQL Server in PowerShell

I see a lot of posts on monitoring sql server that use a “Servers.txt” to iterate the server names.  We (and I imagine a lot of other places as well) store our server information in sql server and not a text file.  Here is how you get said list of servers directly from sql server instead of a text file:

Set-Location SQLSERVER:\SQL\SERVERNAME\DEFAULT
$Servers = Invoke-Sqlcmd -Query "SELECT
       ServerName      
   FROM dbo.[Servers];"
   
foreach($server in $Servers)
{
       Write-Host $server.ServerName
}

You’ll need to load the sql server snapin for this to work correctly.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: