Powershell and SQL Server – 4- List Databases from Multiple SQL Server Instance with Invoke-Sqlcmd

Get the database list from Multiple SQL Instances.Create a Server.txt and populate it with SQL Instance Name and access the content of file in an array.

To access the Server.txt content in an array and loop it for each server

$SQLserverDB=@() #Array variable
$SQLserverDB=Get-Content "C:\PowershellScript\ServerList.txt"
if (-not (Get-Module SQLPS)) 
    {Import-Module SQLPS} 
#Get list of server from text files
$SQLserverDB=@() 
$SQLserverDB=Get-Content "C:\PowershellScript\ServerList.txt"

    foreach($SqlServer in $SQLserverDB)
    {
    Write-Host "|- SQL Server : " $SqlServer -ForegroundColor Yellow

        $result=Invoke-Sqlcmd -ServerInstance $SqlServer  -Database master -Query "SELECT * FROM sys.sysdatabases" -QueryTimeout 0
 
         foreach ($dbname  in $result)
         {
            write-host " |- "$dbname.name           
         }
     }

sqlcmd2

 

Leave a Reply

Your email address will not be published. Required fields are marked *