Book Image

SQL Server 2014 with PowerShell v5 Cookbook

By : Donabel Santos
Book Image

SQL Server 2014 with PowerShell v5 Cookbook

By: Donabel Santos

Overview of this book

Table of Contents (21 chapters)
SQL Server 2014 with PowerShell v5 Cookbook
Credits
About the Author
Acknowledgments
About the Reviewers
www.PacktPub.com
Preface
Index

Executing SQL query to multiple servers


This recipe executes a predefined SQL query to multiple SQL Server instances specified in a text file.

Getting ready

In this recipe, we will connect to multiple SQL Server instances and execute a SQL command against all of them.

Identify the available instances for you to run your query on. Once you have identified all the instances you want to execute the command to, create a text file in C:\Temp called sqlinstances.txt and put each instance name per line in that file. For example:

localhost
localhost\SQL01

How to do it...

Let's list the steps required to complete the task:

  1. Open PowerShell ISE as administrator.

  2. Import the SQLPS module:

    #import SQL Server module
    Import-Module SQLPS -DisableNameChecking
  3. Add the following script and run:

    #replace this with your own file that contains
    #a list of instances you want to send the query to
    
    $instances = Get-Content "C:\Temp\sqlinstances.txt"
    $query = "SELECT @@SERVERNAME 'SERVERNAME', @@VERSION 'VERSION'"
    $databasename...