Run a specific query across all servers using powershell

,

Open Powershell in admin mode

Copy and Paste the script

Make sure you change the path of the serverlist with your valid sql server details.

Finally, Run it.

$OutputPath = "C:\Powershell\SQL Script\NO_DB_Permissions\output.txt";
$cyclecount = 1

try
{

foreach ($svr in get-content "C:\Powershell\serverlist.txt")
{ 
          "****SERVER NAME****	:	$($svr)" | out-file $OutputPath  -append
        "----------------------------------------------------------------------" | out-file $OutputPath  -append
 
         Write-Host "Processing Server: $($svr), Cycle : $($cyclecount)" -Fore Red 
         Invoke-Sqlcmd -inputfile "C:\Powershell\SQL Script\NO_DB_Permissions\nodbpermissions.sql" -ServerInstance $svr  | Out-File -filepath $OutputPath -append
        
           
         Write-Host "Processing completed on Server: $($svr)" -Fore Green;
         $cyclecount += 1
        
}
}
catch
      {
                Write-Warning "Error processing command";
                $error[0];
                $Exception = $Error[0].Exception
               
      }

finally
  {
   $ErrorActionPrefernce = $eap
  }

Rate

4.8 (5)

Share

Share

Rate

4.8 (5)