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:

$Servers = Invoke-Sqlcmd -Query "SELECT
   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.

Leave a Reply

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

You are commenting using your 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 )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.