Rather than issuing a query per instance via SQL Server Management Studio, we are trying to create a powershell script to query multiple instances by going through a loop referencing a text file where it has let's say 100 SQL Server instances. Go through each SQL Server instance, issue a query, and export to CSV.
The below is the powershell script we currently have:
$ServerInstance = "C:\Users\<NAME>\Documents\InstanceList.txt"
foreach ($i in $ServerInstance)
{
$sql = "SELECT
DB_NAME(dbid) as DBName,
COUNT(dbid) as NumberOfConnections,
RTRIM(loginame) as LoginName,
RTRIM(Hostname) As HostName, Login_Time,Program_name
FROM
sys.sysprocesses
WHERE --DB_NAME(dbid) = 'genesys_wfm' and
dbid > 5
--and HostName = 'xxxx'
and loginame not in ('NT AUTHORITY\SYSTEM','ACE','domain\xxxx')
GROUP BY
dbid, loginame,Hostname, Login_Time,Program_name
order by Login_Time desc;"
Invoke-Sqlcmd -ServerInstance $i -Query $sql -ConnectionTimeout 60 -QueryTimeout 99999
The below is the InstanceList.txt:
servername\instance name1
servername2\instance name2
and so forth.
$ServerInstance = get-content "C:\Users\Documents\InstanceList.txt"