Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon
SQL Server 2014 with Powershell v5 Cookbook
SQL Server 2014 with Powershell v5 Cookbook

SQL Server 2014 with Powershell v5 Cookbook: Over 150 real-world recipes to simplify database management, automate repetitive tasks, and enhance your productivity

Arrow left icon
Profile Icon Donabel Santos
Arrow right icon
€18.99 per month
Full star icon Full star icon Full star icon Half star icon Empty star icon 3.4 (5 Ratings)
Paperback Dec 2015 760 pages 1st Edition
eBook
€8.99 €39.99
Paperback
€49.99
Subscription
Free Trial
Renews at €18.99p/m
Arrow left icon
Profile Icon Donabel Santos
Arrow right icon
€18.99 per month
Full star icon Full star icon Full star icon Half star icon Empty star icon 3.4 (5 Ratings)
Paperback Dec 2015 760 pages 1st Edition
eBook
€8.99 €39.99
Paperback
€49.99
Subscription
Free Trial
Renews at €18.99p/m
eBook
€8.99 €39.99
Paperback
€49.99
Subscription
Free Trial
Renews at €18.99p/m

What do you get with a Packt Subscription?

Free for first 7 days. €18.99 p/m after that. Cancel any time!
Product feature icon Unlimited ad-free access to the largest independent learning library in tech. Access this title and thousands more!
Product feature icon 50+ new titles added per month, including many first-to-market concepts and exclusive early access to books as they are being written.
Product feature icon Innovative learning tools, including AI book assistants, code context explainers, and text-to-speech.
Product feature icon Thousands of reference materials covering every tech concept you need to stay up to date.
Subscribe now
View plans & pricing
Table of content icon View table of contents Preview book icon Preview Book

SQL Server 2014 with Powershell v5 Cookbook

Chapter 2. SQL Server and PowerShell Basic Tasks

In this chapter, we will cover:

  • Listing SQL Server instances
  • Discovering SQL Server services
  • Starting/stopping SQL Server services
  • Listing SQL Server configuration settings
  • Changing SQL Server Instance configurations
  • Searching for database objects
  • Scripting SQL Server Stored Procedures
  • Creating a database
  • Altering database properties
  • Dropping a database
  • Changing a database owner
  • Creating a table
  • Creating a view
  • Creating a stored procedure
  • Creating a user defined function
  • Creating a trigger
  • Creating an index
  • Executing a query / SQL script
  • Performing bulk export using Invoke-SqlCmd
  • Performing bulk export using the bcp command-line utility
  • Performing bulk import using BULK INSERT
  • Performing bulk import using the bcp command-line utility
  • Connecting to an Azure SQL database
  • Creating a table in an Azure SQL database

Introduction

In this chapter, we will discuss scripts and snippets of code that accomplish basic SQL Server tasks using PowerShell. We will start with simple tasks such as listing SQL Server instances and creating objects such as tables, indexes, stored procedures, and functions to get you comfortable with working with SQL Server programmatically.

You will find that many of the recipes can be accomplished using PowerShell and SQL Management Objects (SMO). SMO is a library that exposes SQL Server classes that allow programmatic manipulation and automation of many database tasks. For some recipes, we will also explore alternative ways of accomplishing the same tasks using different native PowerShell cmdlets.

Note

SMO is explained in more detail in Chapter 1, Getting Started with SQL Server and PowerShell.

However, even if we are exploring how to create some common database objects using PowerShell, keep in mind that PowerShell will not always be the best tool for the task. There will be tasks...

Listing SQL Server instances

In this recipe, we will list all SQL Server instances in the local network.

Getting ready

Log in to the server that has your SQL Server development instance as an administrator.

How to do it...

Let's look at the steps to list your SQL Server instances:

  1. Open PowerShell ISE as administrator.
  2. Let's use the Start-Service cmdlet to start the SQL Browser service:
    Import-Module SQLPS -DisableNameChecking
    
    #out of the box, the SQLBrowser is disabled. To enable:
    Set-Service SQLBrowser -StartupType Automatic
    
    #sql browser must be installed and running for us
    #to discover SQL Server instances
    Start-Service "SQLBrowser"
  3. Next, you need to create a ManagedComputer object to get access to instances. Type the following script and run:
    $instanceName = "localhost"
    $managedComputer = New-Object Microsoft.SqlServer.Management.Smo.Wmi.ManagedComputer $instanceName
    
    #list server instances
    $managedComputer.ServerInstances

    Your result should look similar to the...

Discovering SQL Server services

In this recipe, we will enumerate all SQL Server services and list their statuses.

Getting ready

Check which SQL Server services are installed in your instance. Go to Start | Run and type services.msc. You should see a screen similar to this:

Getting ready

How to do it...

Let's assume you are running this script on the server box:

  1. Open PowerShell ISE as administrator.
  2. Add the following code and execute:
    Import-Module SQLPS -DisableNameChecking
    
    #you can replace localhost with your instance name
    $instanceName = "localhost"
    $managedComputer = New-Object Microsoft.SqlServer.Management.Smo.Wmi.ManagedComputer $instanceName
    
    #list services
    $managedComputer.Services |
    Select-Object Name, Type, ServiceState, DisplayName |
    Format-Table -AutoSize

    Your result will look similar to the one shown in the following screenshot:

    How to do it...

    Items listed in your screen will vary depending on the features installed and running in your instance

  3. Confirm that these are the services that exist in your...

Starting/stopping SQL Server services

This recipe describes how to start and/or stop SQL Server services.

Getting ready

Check which SQL Services are installed in your machine. Go to Start | Run and type services.msc. You should see a screen similar to this:

Getting ready

How to do it...

Let's look at the steps to toggle your SQL Server services states:

  1. Open PowerShell ISE as administrator.
  2. Add the following code:
    $verbosepreference = "Continue"
    $services = @("SQLBrowser", "ReportServer")
    $hostName = "localhost"
    
    $services |
    ForEach-Object {
       $service = Get-Service -Name $_
       if($service.Status -eq "Stopped")
       {
          Write-Verbose "Starting $($service.Name) ...."
          Start-Service -Name $service.Name
       }
       else
       {
          Write-Verbose "Stopping $($service.Name) ...."
          Stop-Service -Name $service.Name
       }
    }
    $verbosepreference = "SilentlyContinue"

    Note

    Be careful; the status may return prematurely as "started...

Listing SQL Server configuration settings

This recipe walks through how to list SQL Server configurable and nonconfigurable instance settings using PowerShell.

How to do it...

Let's look at the steps involved in listing SQL Server configuration settings:

  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

    To explore what members and methods are included in the SMO server, use the following:

    #Explore: get all properties available for a server object
    #see http://msdn.microsoft.com/en-us/library/ms212724.aspx
    
    $server |
    Get-Member |
    Where-Object MemberType -eq "Property"

    First, let's explore the Information class.

    #The Information class lists nonconfigurable
    #instance settings, like BuildNumber...

Changing SQL Server Instance configurations

This recipe discusses how to change instance configuration settings using PowerShell.

Getting ready

For this recipe, we will perform the following tasks:

  • Change fill factor to 60 percent
  • Enable SQL Server Agent
  • Set Minimum Server Memory to 500 MB
  • Change authentication method to Mixed

How to do it...

Let's change some SQL Server settings using PowerShell:

  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:
    <#
    run value vs config value
    config_value," is what the setting has been set to (but may or may not be what SQL Server is actually running now. Some settings don't go into effect until SQL Server has been restarted, or...

Introduction


In this chapter, we will discuss scripts and snippets of code that accomplish basic SQL Server tasks using PowerShell. We will start with simple tasks such as listing SQL Server instances and creating objects such as tables, indexes, stored procedures, and functions to get you comfortable with working with SQL Server programmatically.

You will find that many of the recipes can be accomplished using PowerShell and SQL Management Objects (SMO). SMO is a library that exposes SQL Server classes that allow programmatic manipulation and automation of many database tasks. For some recipes, we will also explore alternative ways of accomplishing the same tasks using different native PowerShell cmdlets.

Note

SMO is explained in more detail in Chapter 1, Getting Started with SQL Server and PowerShell.

However, even if we are exploring how to create some common database objects using PowerShell, keep in mind that PowerShell will not always be the best tool for the task. There will be tasks...

Listing SQL Server instances


In this recipe, we will list all SQL Server instances in the local network.

Getting ready

Log in to the server that has your SQL Server development instance as an administrator.

How to do it...

Let's look at the steps to list your SQL Server instances:

  1. Open PowerShell ISE as administrator.

  2. Let's use the Start-Service cmdlet to start the SQL Browser service:

    Import-Module SQLPS -DisableNameChecking
    
    #out of the box, the SQLBrowser is disabled. To enable:
    Set-Service SQLBrowser -StartupType Automatic
    
    #sql browser must be installed and running for us
    #to discover SQL Server instances
    Start-Service "SQLBrowser"
  3. Next, you need to create a ManagedComputer object to get access to instances. Type the following script and run:

    $instanceName = "localhost"
    $managedComputer = New-Object Microsoft.SqlServer.Management.Smo.Wmi.ManagedComputer $instanceName
    
    #list server instances
    $managedComputer.ServerInstances

    Your result should look similar to the one shown in the following screenshot...

Discovering SQL Server services


In this recipe, we will enumerate all SQL Server services and list their statuses.

Getting ready

Check which SQL Server services are installed in your instance. Go to Start | Run and type services.msc. You should see a screen similar to this:

How to do it...

Let's assume you are running this script on the server box:

  1. Open PowerShell ISE as administrator.

  2. Add the following code and execute:

    Import-Module SQLPS -DisableNameChecking
    
    #you can replace localhost with your instance name
    $instanceName = "localhost"
    $managedComputer = New-Object Microsoft.SqlServer.Management.Smo.Wmi.ManagedComputer $instanceName
    
    #list services
    $managedComputer.Services |
    Select-Object Name, Type, ServiceState, DisplayName |
    Format-Table -AutoSize

    Your result will look similar to the one shown in the following screenshot:

    Items listed in your screen will vary depending on the features installed and running in your instance

  3. Confirm that these are the services that exist in your server. Check...

Starting/stopping SQL Server services


This recipe describes how to start and/or stop SQL Server services.

Getting ready

Check which SQL Services are installed in your machine. Go to Start | Run and type services.msc. You should see a screen similar to this:

How to do it...

Let's look at the steps to toggle your SQL Server services states:

  1. Open PowerShell ISE as administrator.

  2. Add the following code:

    $verbosepreference = "Continue"
    $services = @("SQLBrowser", "ReportServer")
    $hostName = "localhost"
    
    $services |
    ForEach-Object {
       $service = Get-Service -Name $_
       if($service.Status -eq "Stopped")
       {
          Write-Verbose "Starting $($service.Name) ...."
          Start-Service -Name $service.Name
       }
       else
       {
          Write-Verbose "Stopping $($service.Name) ...."
          Stop-Service -Name $service.Name
       }
    }
    $verbosepreference = "SilentlyContinue"

    Note

    Be careful; the status may return prematurely as "started" when in fact the service is still in the "starting" state.

  3. Execute and confirm that the...

Listing SQL Server configuration settings


This recipe walks through how to list SQL Server configurable and nonconfigurable instance settings using PowerShell.

How to do it...

Let's look at the steps involved in listing SQL Server configuration settings:

  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

    To explore what members and methods are included in the SMO server, use the following:

    #Explore: get all properties available for a server object
    #see http://msdn.microsoft.com/en-us/library/ms212724.aspx
    
    $server |
    Get-Member |
    Where-Object MemberType -eq "Property"

    First, let's explore the Information class.

    #The Information class lists nonconfigurable
    #instance settings, like BuildNumber,
    #OSVersion, ProductLevel etc...

Changing SQL Server Instance configurations


This recipe discusses how to change instance configuration settings using PowerShell.

Getting ready

For this recipe, we will perform the following tasks:

  • Change fill factor to 60 percent

  • Enable SQL Server Agent

  • Set Minimum Server Memory to 500 MB

  • Change authentication method to Mixed

How to do it...

Let's change some SQL Server settings using PowerShell:

  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:

    <#
    run value vs config value
    config_value," is what the setting has been set to (but may or may not be what SQL Server is actually running now. Some settings don't go into effect until SQL Server has been restarted, or until the RECONFIGURE WITH...

Searching for database objects


In this recipe, we will search database objects based on a search string using PowerShell.

Getting ready

We will use the AdventureWorks2014 database in this recipe and look for SQL Server objects with the word Product in it.

To get an idea of what we are expecting to retrieve, run the following script in SQL Server Management Studio:

USE AdventureWorks2014
GO
SELECT
  *
FROM
  sys.objects
WHERE
  name LIKE '%Product%'
   -- check only for table, view, function
   -- or stored procedure
  AND [type] IN ('U', 'FN', 'P', 'V')
ORDER BY
  [type]

This will get you 23 results. Remember this number.

How to do it...

Let's see how we can search for objects in your SQL Server database using PowerShell:

  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...

Scripting SQL Server Stored Procedures


In this recipe, we will explore how to script SQL Server objects, specifically; how to script all non-system and unencrypted stored procedures in a database and save them individually in their own .sql files.

Getting ready

We will use the AdventureWorks2014 database in this recipe. Before we start, let's check which stored procedures are available in this database so that we can cross-check against the scripts we are going to create later.

Open SQL Server Management Studio and navigate to the Programmability node under AdventureWorks2014. You should see a list of stored procedures as shown in the following screenshot:

How to do it...

Let's see how we can script stored procedures in your SQL Server database using PowerShell:

  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...

Creating a database


This recipe walks through creating a database with default properties using PowerShell.

Getting ready

In this example, we are going to create a database called TestDB, and we assume that this database does not yet exist in your instance.

For your reference, the equivalent T-SQL code of this task is as follows:

CREATE DATABASE TestDB

How to do it...

Follow these steps to create a simple database in SQL Server:

  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:

    #database TestDB with default settings
    #assumption is that this database does not yet exist
    $dbName = "TestDB"
    $db = New-Object -TypeName Microsoft.SqlServer.Management.Smo.Database($server, $dbName)
    $db.Create()...

Altering database properties


This recipe shows you how to change database properties using SMO and PowerShell.

Getting ready

Create a database called TestDB by following the steps in the Creating a database recipe.

Using TestDB, we will perform the following tasks:

  • Change ANSI NULLS Enabled to False

  • Change ANSI PADDING Enabled to False

  • Change compatibility version to 110 (SQL Server 2012)

  • Restrict user access to RESTRICTED_USER

  • Set the database to Read Only

How to do it...

Let's look at the steps involved in altering databases using PowerShell:

  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

    Add the following script and run:

    #database
    $dbName = "TestDB"
    
    #we are going to assume db exists
    $db = $server.Databases[$dbName...

Dropping a database


This recipe shows how you can drop a database using PowerShell and SMO.

Getting ready

This task assumes you have created a database called TestDB. If you don't have it, create the database TestDB by following the steps in the Creating a database recipe.

How to do it...

Here are the steps to drop your TestDB database:

  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 = "TestDB"
    
    #need to check if database exists, and if it does, drop it
    $db = $server.Databases[$dbName]
    if ($db)
    {
          #we will use KillDatabase instead of Drop
          #Kill database will drop active connections before
          #dropping the database
          $server.KillDatabase($dbName)
    }

How it works...

Changing database owner


This recipe shows how to programmatically change a SQL Server database owner.

Getting ready

This task assumes you have created a database called TestDB, and a Windows account QUERYWORKS\srogers. QUERYWORKS\srogers has been created in our test VM.

Note

For more information, see Appendix B, Create a SQL Server VM.

If you don't have it, create the database TestDB by following the steps in the Creating a database recipe.

How to do it...

Let's look at the steps involved in changing a database owner:

  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:

    #create database handle
    $dbName = "TestDB"
    $db = $server.Databases[$dbName]
    
    #display current owner
    $db.Owner
    
    #change owner...

Creating a table


This recipe shows how to create a table using PowerShell and SMO.

Getting ready

We will use the AdventureWorks2014 database to create a table named Student, which has five columns and two default constraints. To give you a better idea of what we are trying to achieve, the equivalent T-SQL script needed to create this table is as follows:

USE AdventureWorks2014
GO
CREATE TABLE [dbo].[Student](
  [StudentID] [INT] IDENTITY(1,1) NOT NULL,
  [FName] [VARCHAR](50) NULL,
  [LName] [VARCHAR](50) NOT NULL,
  [DateOfBirth] [DATETIME] NULL,
  [Age]  AS (DATEPART(YEAR,GETDATE())-DATEPART(YEAR,[DateOfBirth])),
    CONSTRAINT [PK_Student_StudentID] PRIMARY KEY CLUSTERED
   (
     [StudentID] ASC
   )
)

GO
ALTER TABLE [dbo].[Student] ADD  CONSTRAINT [DF_Student_LName] DEFAULT ('Doe') FOR [LName]
GO

ALTER TABLE [dbo].[Student] ADD  CONSTRAINT [DF_Student_DateOfBirth]  DEFAULT ('1800-00-00') FOR [DateOfBirth]
GO

How to do it...

Let's create the Student table using PowerShell:

  1. Open PowerShell...

Creating a view


This recipe shows how to create a view using PowerShell and SMO.

Getting ready

We will use the Person.Person table in the AdventureWorks2014 database for this recipe.

To give you an idea what we are attempting to create in this recipe, this is the T-SQL equivalent.

CREATE VIEW dbo.vwVCPerson
AS
SELECT
   TOP 100
  BusinessEntityID,
  LastName,
  FirstName
FROM
  Person.Person
WHERE
    PersonType = 'IN'
GO

How to do it...

Let's check out the steps to create a view using PowerShell:

  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

    Add the following script and run:

    $dbName = "AdventureWorks2014"
    $db = $server.Databases[$dbName]
    $viewName = "vwVCPerson"
    $view = $db.Views[$viewName]
    
    #if view exists, drop it...

Creating a stored procedure


This recipe shows how to create an encrypted stored procedure using SMO and PowerShell.

Getting ready

The T-SQL equivalent of the encrypted stored procedure we are about to recreate in PowerShell is as follows:

CREATE PROCEDURE [dbo].[uspGetPersonByLastName]
@LastName [varchar](50)
WITH ENCRYPTION
AS

SELECT
   TOP 10
   BusinessEntityID,
   LastName
FROM
   Person.Person
WHERE
   LastName = @LastName

How to do it...

Follow these steps to create the uspGetPersonByLastName stored procedure using PowerShell:

  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

    Add the following script and run:

    $dbName = "AdventureWorks2014"
    $db = $server.Databases[$dbName]
    
    #storedProcedure class on MSDN:
    #http:/...

Creating a trigger


This recipe shows how to programmatically create a trigger in SQL Server using SMO and PowerShell

Getting ready

For this recipe, we will use the Person.Person table in the AdventureWorks2014 database. We will create a trivial AFTER trigger that merely displays values from the inserted and deleted tables upon firing.

The following is the T-SQL equivalent of what we are going to accomplish programmatically in this section:

CREATE TRIGGER [Person].[tr_u_Person]
ON [Person].[Person]
AFTER  UPDATE
AS

  SELECT
     GETDATE() AS UpdatedOn,
     SYSTEM_USER AS UpdatedBy,
     i.LastName AS NewLastName,
     i.FirstName AS NewFirstName,
     d.LastName AS OldLastName,
     d.FirstName AS OldFirstName
  FROM
     inserted i
     INNER JOIN deleted d
     ON i.BusinessEntityID = d.BusinessEntityID

How to do it...

Let's follow these steps to create an AFTER trigger in PowerShell:

  1. Open PowerShell ISE as administrator.

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

    #import SQL...

Creating an index


This recipe shows how to create a nonclustered index with an included column using PowerShell and SMO.

Getting ready

We will use the Person.Person table in the AdventureWorks2014 database. We will create a nonclustered index on FirstName, LastName, and include MiddleName. The T-SQL equivalent of this task is as follows:

CREATE NONCLUSTERED INDEX [idxLastNameFirstName]
ON [Person].[Person]
(
  [LastName] ASC,
  [FirstName] ASC
)
INCLUDE ([MiddleName])
GO

How to do it...

Let's check out how we can create an index using PowerShell:

  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]
    
    $tableName = "Person"
    $schemaName...

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...
Left arrow icon Right arrow icon
Download code icon Download Code

Description

PowerShell can be leveraged when automating and streamlining SQL Server tasks. PowerShell comes with a rich set of cmdlets, and integrates tightly with the .NET framework. Its scripting capabilities are robust and flexible, allowing you to simplify automation and integration across different Microsoft applications and components. The book starts with an introduction to the new features in SQL Server 2014 and PowerShell v5 and the installation of SQL Server. You will learn about basic SQL Server administration tasks and then get to know about some security-related topics such as the authentication mode and assigning permissions. Moving on, you will explore different methods to back up and restore your databases and perform advanced administration tasks such as working with Policies, Filetables, and SQL audits. The next part of the book covers more advanced HADR tasks such as log shipping and data mirroring, and then shows you how to develop your server to work with BLOB, XML, and JSON. Following on from that, you will learn about SQL Server's BI stack, which includes SSRS reports, the SSIS package, and the SSAS cmdlet and database. Snippets not specific to SQL Server will help you perform tasks quickly on SQL servers. Towards the end of the book, you will find some useful information, which includes a PowerShell tutorial for novice users, some commonly-used PowerShell and SQL Server syntax, and a few online resources. Finally, you will create your own SQL Server Sandbox VMs. All these concepts will help you to efficiently manage your administration tasks.

Who is this book for?

If you are a SQL Server database professional (DBA, developer, or BI developer) who wants to use PowerShell to automate, integrate, and simplify database tasks, this books is for you. Prior knowledge of scripting would be helpful, but it is not necessary.

What you will learn

  • Explore database objects and execute queries on multiple servers
  • Manage and monitor the running of SQL Server services and accounts
  • Back up and restore databases
  • Create an inventory of database properties and server configuration settings
  • Maintain permissions and security for users
  • Work with CLR assemblies, XML, and BLOB objects in SQL
  • Manage and deploy SSIS packages and SSRS reports

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Dec 04, 2015
Length: 760 pages
Edition : 1st
Language : English
ISBN-13 : 9781785283321
Vendor :
Microsoft
Category :
Languages :
Tools :

What do you get with a Packt Subscription?

Free for first 7 days. €18.99 p/m after that. Cancel any time!
Product feature icon Unlimited ad-free access to the largest independent learning library in tech. Access this title and thousands more!
Product feature icon 50+ new titles added per month, including many first-to-market concepts and exclusive early access to books as they are being written.
Product feature icon Innovative learning tools, including AI book assistants, code context explainers, and text-to-speech.
Product feature icon Thousands of reference materials covering every tech concept you need to stay up to date.
Subscribe now
View plans & pricing

Product Details

Publication date : Dec 04, 2015
Length: 760 pages
Edition : 1st
Language : English
ISBN-13 : 9781785283321
Vendor :
Microsoft
Category :
Languages :
Tools :

Packt Subscriptions

See our plans and pricing
Modal Close icon
€18.99 billed monthly
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Simple pricing, no contract
€189.99 billed annually
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just €5 each
Feature tick icon Exclusive print discounts
€264.99 billed in 18 months
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just €5 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total 120.97
SQL Server 2014 with Powershell v5 Cookbook
€49.99
PowerShell for SQL Server Essentials
€24.99
SQL Server 2016 Reporting Services Cookbook
€45.99
Total 120.97 Stars icon
Banner background image

Table of Contents

14 Chapters
1. Getting Started with SQL Server and PowerShell Chevron down icon Chevron up icon
2. SQL Server and PowerShell Basic Tasks Chevron down icon Chevron up icon
3. Basic Administration Chevron down icon Chevron up icon
4. Security Chevron down icon Chevron up icon
5. Backup and Restore Chevron down icon Chevron up icon
6. Advanced Administration Chevron down icon Chevron up icon
7. Audit and Policies Chevron down icon Chevron up icon
8. High Availability with AlwaysOn Chevron down icon Chevron up icon
9. SQL Server Development Chevron down icon Chevron up icon
10. Business Intelligence Chevron down icon Chevron up icon
11. Helpful PowerShell Snippets Chevron down icon Chevron up icon
A. PowerShell Primer Chevron down icon Chevron up icon
B. Creating a SQL Server VM Chevron down icon Chevron up icon
Index Chevron down icon Chevron up icon

Customer reviews

Rating distribution
Full star icon Full star icon Full star icon Half star icon Empty star icon 3.4
(5 Ratings)
5 star 60%
4 star 0%
3 star 0%
2 star 0%
1 star 40%
Alan Jaeger Mar 04, 2016
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Aktuell kenne ich kein besseres Buch mit diesem Fokus, deshalb bekommt es volle Sternzahl, wenn auch in Punkto Sprache, deutsche Ausgabe, Luft nach hoben ist.
Amazon Verified review Amazon
Enrique Thedy Jan 25, 2016
Full star icon Full star icon Full star icon Full star icon Full star icon 5
The book is very complete and the explanations are clear! An imprescindible complement for any SQL Server user
Amazon Verified review Amazon
Dan Q Yang May 08, 2016
Full star icon Full star icon Full star icon Full star icon Full star icon 5
good one!
Amazon Verified review Amazon
txtester Aug 20, 2019
Full star icon Empty star icon Empty star icon Empty star icon Empty star icon 1
I am using PowerShell on a greater scale, especially with SQL Server, and I have bought previous books with this subject matter. None of the PowerShell books I have bought are really no better than the Blog Posts and public boards, but at least they have some organization that can be useful. This book has none. Not sure what the other two reviewers were looking at, but the several times I have tried to get useful information out of this book, it is simply too frustrating to find anything. Since the cost of this book was higher than most of the other books I have bought (@ $30), I did expect better.
Amazon Verified review Amazon
kit Apr 27, 2020
Full star icon Empty star icon Empty star icon Empty star icon Empty star icon 1
現在のpowershell では対応しないように思います。
Amazon Verified review Amazon
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

What is included in a Packt subscription? Chevron down icon Chevron up icon

A subscription provides you with full access to view all Packt and licnesed content online, this includes exclusive access to Early Access titles. Depending on the tier chosen you can also earn credits and discounts to use for owning content

How can I cancel my subscription? Chevron down icon Chevron up icon

To cancel your subscription with us simply go to the account page - found in the top right of the page or at https://subscription.packtpub.com/my-account/subscription - From here you will see the ‘cancel subscription’ button in the grey box with your subscription information in.

What are credits? Chevron down icon Chevron up icon

Credits can be earned from reading 40 section of any title within the payment cycle - a month starting from the day of subscription payment. You also earn a Credit every month if you subscribe to our annual or 18 month plans. Credits can be used to buy books DRM free, the same way that you would pay for a book. Your credits can be found in the subscription homepage - subscription.packtpub.com - clicking on ‘the my’ library dropdown and selecting ‘credits’.

What happens if an Early Access Course is cancelled? Chevron down icon Chevron up icon

Projects are rarely cancelled, but sometimes it's unavoidable. If an Early Access course is cancelled or excessively delayed, you can exchange your purchase for another course. For further details, please contact us here.

Where can I send feedback about an Early Access title? Chevron down icon Chevron up icon

If you have any feedback about the product you're reading, or Early Access in general, then please fill out a contact form here and we'll make sure the feedback gets to the right team. 

Can I download the code files for Early Access titles? Chevron down icon Chevron up icon

We try to ensure that all books in Early Access have code available to use, download, and fork on GitHub. This helps us be more agile in the development of the book, and helps keep the often changing code base of new versions and new technologies as up to date as possible. Unfortunately, however, there will be rare cases when it is not possible for us to have downloadable code samples available until publication.

When we publish the book, the code files will also be available to download from the Packt website.

How accurate is the publication date? Chevron down icon Chevron up icon

The publication date is as accurate as we can be at any point in the project. Unfortunately, delays can happen. Often those delays are out of our control, such as changes to the technology code base or delays in the tech release. We do our best to give you an accurate estimate of the publication date at any given time, and as more chapters are delivered, the more accurate the delivery date will become.

How will I know when new chapters are ready? Chevron down icon Chevron up icon

We'll let you know every time there has been an update to a course that you've bought in Early Access. You'll get an email to let you know there has been a new chapter, or a change to a previous chapter. The new chapters are automatically added to your account, so you can also check back there any time you're ready and download or read them online.

I am a Packt subscriber, do I get Early Access? Chevron down icon Chevron up icon

Yes, all Early Access content is fully available through your subscription. You will need to have a paid for or active trial subscription in order to access all titles.

How is Early Access delivered? Chevron down icon Chevron up icon

Early Access is currently only available as a PDF or through our online reader. As we make changes or add new chapters, the files in your Packt account will be updated so you can download them again or view them online immediately.

How do I buy Early Access content? Chevron down icon Chevron up icon

Early Access is a way of us getting our content to you quicker, but the method of buying the Early Access course is still the same. Just find the course you want to buy, go through the check-out steps, and you’ll get a confirmation email from us with information and a link to the relevant Early Access courses.

What is Early Access? Chevron down icon Chevron up icon

Keeping up to date with the latest technology is difficult; new versions, new frameworks, new techniques. This feature gives you a head-start to our content, as it's being created. With Early Access you'll receive each chapter as it's written, and get regular updates throughout the product's development, as well as the final course as soon as it's ready.We created Early Access as a means of giving you the information you need, as soon as it's available. As we go through the process of developing a course, 99% of it can be ready but we can't publish until that last 1% falls in to place. Early Access helps to unlock the potential of our content early, to help you start your learning when you need it most. You not only get access to every chapter as it's delivered, edited, and updated, but you'll also get the finalized, DRM-free product to download in any format you want when it's published. As a member of Packt, you'll also be eligible for our exclusive offers, including a free course every day, and discounts on new and popular titles.