How to get list of databases from multiple servers

advertisement
How to get list of databases from multiple servers
Sounds very easy then done. When some one ask you to get a list of databases from
server we do remember “sys.databases” and if some one ask from 5-10 servers we
connect to each instance in sql server and get the list of databases. Query will be like
“Select name as [database name] ,@@servername as [server name]from sys.databases”
But what if some one asks you to get list of databases from 100+ servers. It will take
days to finish manually but powershell can get this done in a click
So how to do this
1. First find a server in domain having powershell installed
2. Create directory “X:\Monitoring_Automation\”
3. Create files in above directory
a. Serverlist <servers.txt>
b. Powershell script <dblist.ps1>
c. Batch file to call PS1 file <GetDBlist.bat>
d. Output file to collect list of database <Output.csv>
4. In “X:\Monitoring_Automation\Servers.txt” write all server name separated with
enter from which you want to get database list
5. In “X:\Monitoring_Automation\ dblist.ps1” place below code
/*********** Code Start****************/
#File name : X:\Monitoring_Automation\dbdetail.ps1
#Initializing output path
#$FilePath = "X:\Monitoring_Automation\"
#$OutFile1 = Join-Path -path $FilePath -childPath ("dblist_" + (getdate).toString('yyyyMMdd_hhmmtt') + ".log")
$OutFile = "X:\Monitoring_Automation\output.csv"
#Running code on each server
foreach ($svr in get-content "X:\Monitoring_Automation\Servers.txt")
{
$con = "server=$svr;database=master;Integrated Security=sspi"
$cmd = "select name , @@servername from sys.databases"
$da = new-object System.Data.SqlClient.SqlDataAdapter ($cmd, $con)
$dt = new-object System.Data.DataTable
$da.fill($dt) | out-null
$svr
$dt | Format-Table -autosize
#$dt | export-csv -noType $OutFile1
$dt >>$OutFile
}
#$dt | export-csv -noType $OutFile1
$end = get-date
write-host "End: " $end
/*****************ENd of Code***********************/
6. In “X:\Monitoring_Automation\ GetDBlist.bat” place below code
/************** CODE START **************/
Powershell.exe “ X:\Monitoring_Automation\dbdetail.ps1”
/************* CODE END *******************/
7. If you will not even create “X:\Monitoring_Automation\output.csv” , powershell
will take care of step
8. Now open command prompt : Run -> CMD -> Go to X:\Monitoring_Automation\
9. Once execution is completed, you will get output in command prompt screen
and in “X:\Monitoring_Automation\output.csv” as well.
10. Copy the output in excel , use data -> text to column option to format and your
report is ready to be sent
You can find same in my blog also for reference:
http://saurabhsinhainblogs.blogspot.in/2013/09/how-to-get-list-of-databasesfrom.html
Download