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 a query/SQL script


This recipe shows how you can execute either a hardcoded query or a SQL Script from PowerShell.

Getting ready

Create a file in your C:\Temp folder called SampleScript.sql. This should contain the following:

SELECT TOP 10 *
FROM Person.Person

How to do it...

The following are the steps in executing a query / SQL script:

  1. Open PowerShell ISE as administrator.

  2. Import the SQLPS module and create a new SMO Server Object:

    #import SQL Server module
    Import-Module SQLPS -DisableNameChecking
    
    #replace this with your instance name
    $instanceName = "localhost"
    $server = New-Object -TypeName Microsoft.SqlServer.Management.Smo.Server -ArgumentList $instanceName
  3. Add the following script and run:

    $dbName = "AdventureWorks2014"
    $db = $server.Databases[$dbName]
    
    #execute a passthrough query, and export to a CSV file
    
    #line continuation in code below only happens at
    #the pipe (|) delimiter
    Invoke-Sqlcmd -Query "SELECT * FROM Person.Person"
    -ServerInstance "$instanceName" -Database $dbName...