Powershell: Loop through Multiple Servers and Export Result to a File

## server list from a string
###   $ServerList = "dev", "qa"  

## serverlist from a file
$ServerList=Get-Content C:\temp\Serverlist.txt

##The combined file
$finalfilepath = "C:\temp\filefinal.csv"
##clear the file content if it exists
if (Test-Path $finalfilepath) {Clear-Content C:\temp\filefinal.csv }

foreach ($CurrentServer in $ServerList) 

##Save one serverinstance as a file
  $csvFilePath ="C:\temp\($CurrentServer)list.csv"
  Invoke-Sqlcmd -Server $CurrentServer -Database master  -Query "SELECT @@servername as 'Server', name as 'DB', convert(varchar(8), getdate(), 1) as 'Date' from sys.databases WHERE database_id > 4 AND database_id NOT IN (select database_id from sys.dm_hadr_database_replica_states)"  -querytimeout 65534  | export-csv $csvFilePath   -NoTypeInformation
	Get-Content  $csvFilePath >>  $finalfilepath

##Open in notepad
notepad C:\temp\filefinal.csv


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