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.