Tuesday, July 23, 2024

Powershell - Run SQL Scripts on Multiple Servers

 You must need SqlServer module is the current PowerShell module to use below script.

The SqlServer module comes with:

  • PowerShell Providers, which enables a simple navigation mechanism similar to file system paths. You can build paths similar to file system paths, where the drive is associated with a SQL Server management object model, and the nodes are based on the object model classes. You can then use familiar commands such as cd (alias for Set-Location) and dir (alias for Get-ChildItem) to navigate the paths similar to the way you navigate folders in a command prompt window. You can use other commands, such as ren (alias for Rename-Item) or del (alias for Remove-Item), to perform actions on the nodes in the path.

  • A set of cmdlets that support actions such as running a sqlcmd script containing Transact-SQL or XQuery statements.

  • The AS provider and cmdlets, which before they were installed separately.

     

    YOU NEED TO  PUT ALL SQL SERVER INSTANCE NAMES IN INSTANCENAME.txt file in order to run below script. I use  this scripts a lot to update or pull many information from different servers.

     

    $ServerList = Get-Content "DRIVE\InstanceName.txt"
    $SourceDatabase = "master"
    $Script1 = "select @@servername"

    ForEach ($ServerName in $ServerList)
    {
        Write-Host $ServerName
        invoke-sqlcmd -ServerInstance $ServerName -Database $SourceDatabase -Query $Script1

    }

     

     Comment your thought regarding this script. Let me know if you need to generate any scripts for your project I will be happy to help you out. 


No comments:

Post a Comment