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
Newsletter Hub
Free Learning
Arrow right icon
timer SALE ENDS IN
0 Days
:
00 Hours
:
00 Minutes
:
00 Seconds
SQL Server 2012 with PowerShell V3 Cookbook
SQL Server 2012 with PowerShell V3 Cookbook

SQL Server 2012 with PowerShell V3 Cookbook:

eBook
€27.98 €39.99
Paperback
€48.99
Subscription
Free Trial
Renews at €18.99p/m

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
OR
Modal Close icon
Payment Processing...
tick Completed

Billing Address

Table of content icon View table of contents Preview book icon Preview Book

SQL Server 2012 with PowerShell V3 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

  • 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 trigger

  • Creating an index

  • Executing a query / SQL script

  • Performing bulk export using Invoke-Sqlcmd

  • Performing bulk export using bcp

  • Performing bulk import using BULK INSERT

  • Performing bulk import using bcp

Introduction


This chapter demonstrates scripts and snippets of code that accomplish some 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, which allows for 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.

Even though we are exploring how to create some common database objects using PowerShell, I would like to note that PowerShell is not always the best tool for the task. There will be...

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

  1. Open the PowerShell console by going to Start | Accessories | Windows PowerShell | Windows PowerShell ISE.

  2. Let's use the Start-Service cmdlet to start SQLBrowser:

    Import-Module SQLPS -DisableNameChecking
    
    #sql browser must be installed and running
    Start-Service "SQLBrowser"
  3. Next, you need to create a ManagedComputer object to get access to instances. Type the following script and run it:

    $instanceName = "KERRIGAN"  
    $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:

    Note that $managedComputer.ServerInstances gives you not only instance names, but also additional properties such as ServerProtocols...

Discovering SQL Server services


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

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 the PowerShell console by going to Start | Accessories | Windows PowerShell | Windows PowerShell ISE.

  2. Add the following code and execute it:

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

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

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

  3. Confirm that these are the services...

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 states for your SQL Server services:

  1. Open the PowerShell console by going to Start | Accessories | Windows PowerShell | Windows PowerShell ISE.

  2. Add the following code. Note that this code will work in both PowerShell V2 and V3:

    $Verbosepreference = "Continue"
    $services = @("SQLBrowser", "ReportServer")
    $hostName = "KERRIGAN"
    
    $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"
  3. Execute and...

Listing SQL Server configuration settings


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

How to do it...

  1. Open the PowerShell ISE. Go to Start | Accessories | Windows PowerShell | Windows PowerShell ISE.

  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 = "KERRIGAN"
    $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 code snippet in PowerShell V3:

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

    In PowerShell V2, you will need to slightly modify your syntax:

    $server | Get-Member | Where {$_.MemberType -eq "Property"}
    #The Information class lists...

Changing SQL Server instance configurations


This recipe walks through how to change instance configuration settings using PowerShell.

Getting ready

For this recipe, we will:

  • Change FillFactor 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 the PowerShell console by going to Start | Accessories | Windows PowerShell | Windows PowerShell ISE.

  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 = "KERRIGAN"
    $server = New-Object -TypeName Microsoft.SqlServer.Management.Smo.Server -ArgumentList $instanceName
  3. Add the following script and run it:

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

Searching for database objects


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

Getting ready

We will use AdventureWorks2008R2, in this exercise, and will look for SQL Server objects with the word "Product" in their names.

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

USE AdventureWorks2008R2
GO
SELECT 
 * 
FROM 
 sys.objects
WHERE 
 name LIKE '%Product%'
 -- filter table level objects only
 AND [type] NOT IN ('C', 'D', 'PK', 'F') 
ORDER BY 
 [type]

This will get you 23 results. Remember this number.

How to do it...

  1. Open the PowerShell console by going to Start | Accessories | Windows PowerShell | Windows PowerShell ISE.

  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 = "KERRIGAN"
    $server = New-Object -TypeName Microsoft.SqlServer.Management.Smo.Server -ArgumentList...

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 for this task is:

CREATE DATABASE TestDB

How to do it...

  1. Open the PowerShell console by going to Start | Accessories | Windows PowerShell | Windows PowerShell ISE.

  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 = "KERRIGAN"
    $server = New-Object -TypeName Microsoft.SqlServer.Management.Smo.Server -ArgumentList $instanceName
  3. Add the following script and run it:

    #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:

  • Change ANSI NULLS Enabled to False

  • Change ANSI PADDING Enabled to False

  • Restrict user access to RESTRICTED_USER

  • Set the database to Read Only

How to do it...

  1. Open the PowerShell console by going to Start | Accessories | Windows PowerShell | Windows PowerShell ISE.

  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 = "KERRIGAN"
    $server = New-Object -TypeName Microsoft.SqlServer.Management.Smo.Server -ArgumentList $instanceName
  3. Add the following script and run

    #database
    $dbName = "TestDB"
    
    #we are going to assume db exists
    $db = $server.Databases[$dbName]
    
    #DatabaseOptions
    #change ANSI NULLS and ANSI PADDING
    $db.DatabaseOptions.AnsiNullsEnabled...

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 haven't, create one by following the steps in the Creating a database recipe.

How to do it...

The following are the steps to drop your TestDB database:

  1. Open the PowerShell console by going to Start | Accessories | Windows PowerShell | Windows PowerShell ISE.

  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 = "KERRIGAN"
    $server = New-Object -TypeName Microsoft.SqlServer.Management.Smo.Server -ArgumentList $instanceName
  3. Add the following script and run it:

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

Changing a 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 that a Windows account QUERYWORKS\aterra. QUERYWORKS\aterra has been created in your test VM.

Note

See Appendix D, Creating a SQL Server VM.

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

How to do it...

  1. Open the PowerShell console by going to Start | Accessories | Windows PowerShell | Windows PowerShell ISE.

  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 = "KERRIGAN"
    $server = New-Object -TypeName Microsoft.SqlServer.Management.Smo.Server -ArgumentList $instanceName
  3. Add the following script and run it:

    #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 AdventureWorks2008R2 database to create a table named Student, which has five columns. 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 AdventureWorks2008R2
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

How to do it...

Let's create the Student table using PowerShell:

  1. Open the PowerShell console by going to Start | Accessories | Windows PowerShell | Windows PowerShell ISE.

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

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 AdventureWorks2008R2 database for this recipe.

To give you an idea of 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'
ORDER BY
    LastName
GO

How to do it...

  1. Open the PowerShell console by going to Start | Accessories | Windows PowerShell | Windows PowerShell ISE.

  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 = "KERRIGAN"
    $server = New-Object -TypeName Microsoft.SqlServer.Management.Smo.Server -ArgumentList $instanceName
  3. Add the following script and run it:

    $dbName = "AdventureWorks2008R2"
    $db = $server.Databases[$dbName]
    $viewName = "vwVCPerson"
    $view = $db...

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 the PowerShell console by going to Start | Accessories | Windows PowerShell | Windows PowerShell ISE.

  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 = "KERRIGAN"
    $server = New-Object -TypeName Microsoft.SqlServer.Management.Smo.Server -ArgumentList $instanceName
  3. Add the following script and run it:

    $dbName = "AdventureWorks2008R2...

Creating a trigger


This recipe demonstrates 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 AdventureWorks2008R2 database. We will create a trivial AFTER trigger that merely displays values from the inserted and deleted records 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 the PowerShell console by going to Start | Accessories | Windows PowerShell | Windows...

Creating an index


This recipe demonstrates how to create a non-clustered index with an included column using PowerShell and SMO.

Getting ready

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

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

How to do it...

  1. Open the PowerShell console by going to Start | Accessories | Windows PowerShell | Windows PowerShell ISE.

  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 = "KERRIGAN"
    $server = New-Object -TypeName Microsoft.SqlServer.Management.Smo.Server -ArgumentList $instanceName
  3. Add the following script and run it:

    $dbName = "AdventureWorks2008R2"
    $db = $server.Databases[$dbName]
    
    $tableName...

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:

SELECT * 
FROM Person.Person

How to do it...

  1. Open the PowerShell console by going to Start | Accessories | Windows PowerShell | Windows PowerShell ISE.

  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 = "KERRIGAN"
    $server = New-Object -TypeName Microsoft.SqlServer.Management.Smo.Server -ArgumentList $instanceName
  3. Add the following script and run it:

    $dbName = "AdventureWorks2008R2"
    $db = $server.Databases[$dbName]
    
    #execute a passthrough query, and export to a CSV file
    Invoke-Sqlcmd `
    -Query "SELECT * FROM Person.Person" `
    -ServerInstance "$instanceName" `
    -Database $dbName | 
    Export-Csv -LiteralPath "C:\Temp\ResultsFromPassThrough.csv" `
    ...

Performing bulk export using Invoke-Sqlcmd


This recipe demonstrates how to export contents of a table to a CSV file using PowerShell and the Invoke-Sqlcmd cmdlet.

Getting ready

Make sure you have access to the AdventureWorks2008R2 database. We will use the Person.Person table.

Create a C:\Temp folder, if you don't already have one on your system.

How to do it...

  1. Open the PowerShell console by going to Start | Accessories | Windows PowerShell | Windows PowerShell ISE.

  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 = "KERRIGAN"
    $server = New-Object -TypeName Microsoft.SqlServer.Management.Smo.Server -ArgumentList $instanceName
  3. Add the following script and run it:

    #database handle
    $dbName = "AdventureWorks2008R2"
    $db = $server.Databases[$dbName]
    
    #export file name
    $exportfile = "C:\Temp\Person_Person.csv"
    
    $query = @"
    SELECT 
       * 
    FROM 
       Person.Person
    "@
    Invoke...

Performing bulk export using bcp


This recipe demonstrates how to export contents of a table to a CSV file using PowerShell and bcp.

Getting ready

Make sure you have access to the AdventureWorks2008R2 database. We will export the Person.Person table to a timestamped text file delimited by a pipe (|).

Create a C:\Temp\Exports folder, if you don't already have it on your system.

How to do it...

  1. Open the PowerShell console by going to Start | Accessories | Windows PowerShell | Windows PowerShell ISE.

  2. Add the following script and run the following code:

    $server = "KERRIGAN"
    $table = "AdventureWorks2008R2.Person.Person"
    $curdate = Get-Date -Format "yyyy-MM-dd_hmmtt"
    
    $foldername = "C:\Temp\Exports\"
    
    #format file name
    $formatfilename = "$($table)_$($curdate).fmt"
    
    #export file name
    $exportfilename = "$($table)_$($curdate).csv"
    
    $destination_exportfilename = "$($foldername)$($exportfilename)"
    $destination_formatfilename = "$($foldername)$($formatfilename)"
    
    #command to generate format file
    $cmdformatfile...

Performing bulk import using BULK INSERT


This recipe will walk you through importing contents of a CSV file to SQL Server using PowerShell and BULK INSERT.

Getting ready

To do a test import, we will first need to create a Person table similar to the Person.Person table from the AdventureWorks2008R2 database, with some slight modifications.

We will create this in the Test schema, and we will remove some of the constraints and keep this table as simple and independent as we can.

To create the table that we need for this exercise, open up Management Studio and run the following code:

CREATE SCHEMA [Test]
GO
CREATE TABLE [Test].[Person](
 [BusinessEntityID] [int] NOT NULL PRIMARY KEY,
 [PersonType] [nchar](2) NOT NULL,
 [NameStyle] [dbo].[NameStyle] NOT NULL,
 [Title] [nvarchar](8) NULL,
 [FirstName] [dbo].[Name] NOT NULL,
 [MiddleName] [dbo].[Name] NULL,
 [LastName] [dbo].[Name] NOT NULL,
 [Suffix] [nvarchar](10) NULL,
 [EmailPromotion] [int] NOT NULL,
 [AdditionalContactInfo] [xml] NULL,
 [Demographics...

Performing bulk import using bcp


This recipe will walk you through the process of importing the contents of a CSV file to SQL Server using PowerShell and bcp.

Getting ready

To do a test import, let's first create a Person table similar to the Person.Person table from the AdventureWorks2008R2 database, with some slight modifications. We will create this in the Test schema, and we will remove some of the constraints and keep this table as simple and independent as we can.

If Test.Person does not yet exist in your environment, let's create it. Open up Management Studio, and run the following code:

CREATE SCHEMA [Test]
GO
CREATE TABLE [Test].[Person](
 [BusinessEntityID] [int] NOT NULL PRIMARY KEY,
 [PersonType] [nchar](2) NOT NULL,
 [NameStyle] [dbo].[NameStyle] NOT NULL,
 [Title] [nvarchar](8) NULL,
 [FirstName] [dbo].[Name] NOT NULL,
 [MiddleName] [dbo].[Name] NULL,
 [LastName] [dbo].[Name] NOT NULL,
 [Suffix] [nvarchar](10) NULL,
 [EmailPromotion] [int] NOT NULL,
 [AdditionalContactInfo] [xml...
Left arrow icon Right arrow icon
Download code icon Download Code

Key benefits

  • Provides over a hundred practical recipes that utilize PowerShell to automate, integrate and simplify SQL Server tasks
  • Offers easy to follow, step-by-step guide to getting the most out of SQL Server and PowerShell
  • Covers numerous guidelines, tips, and explanations on how and when to use PowerShell cmdlets, WMI, SMO, .NET classes or other components
  • Builds a strong foundation that gets you comfortable using PowerShell with SQL Server--empowering you to create more complex scripts that you need in your day-to-day job

Description

PowerShell is Microsoft's new command-line shell and scripting language that promises to simplify automation and integration across different Microsoft applications and components. Database professionals can leverage PowerShell by utilizing its numerous built-in cmdlets, or using any of the readily available .NET classes, to automate database tasks, simplify integration, or just discover new ways to accomplish the job at hand."SQL Server 2012 with PowerShell V3 Cookbook" provides easy-to-follow, practical examples for the busy database professional. Whether you're auditing your servers, or exporting data, or deploying reports, there is a recipe that you can use right away!You start off with basic topics to get you going with SQL Server and PowerShell scripts and progress into more advanced topics to help you manage and administer your SQL Server databases.The first few chapters demonstrate how to work with SQL Server settings and objects, including exploring objects, creating databases, configuring server settings, and performing inventories. The book then deep dives into more administration topics like backup and restore, credentials, policies, jobs.Additional development and BI-specific topics are also explored, including deploying and downloading assemblies, BLOB data, SSIS packages, and SSRS reports. A short PowerShell primer is also provided as a supplement in the Appendix, which the database professional can use as a refresher or occasional reference material. Packed with more than 100 practical, ready-to-use scripts, "SQL Server 2012 with PowerShell V3 Cookbook" will be your go-to reference in automating and managing SQL Server.

Who is this book for?

This book is written for the SQL Server database professional (DBA, developer, BI developer) who wants to use PowerShell to automate, integrate, and simplify database tasks. A little bit of scripting background is helpful, but not necessary.

What you will learn

  • Create an inventory of database properties and server configuration settings
  • Backup and restore databases
  • Execute queries to multiple servers
  • Maintain permissions and security for users
  • Import and export XML into SQL Server
  • Extract CLR assemblies and BLOB objects from the database
  • Explore database objects
  • Manage and deploy SSIS packages and SSRS reports
  • Manage and monitor running SQL Server services and accounts
  • Parse and display the contents of trace files
  • Create SQL Server jobs, alerts and operators
  • Find blocking processes that are hampering your database performance

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Oct 25, 2012
Length: 634 pages
Edition : 1st
Language : English
ISBN-13 : 9781849686471
Concepts :
Tools :

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
OR
Modal Close icon
Payment Processing...
tick Completed

Billing Address

Product Details

Publication date : Oct 25, 2012
Length: 634 pages
Edition : 1st
Language : English
ISBN-13 : 9781849686471
Concepts :
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 135.97
Microsoft SQL Server 2012 Performance Tuning Cookbook
€48.99
Microsoft SQL Server 2012 Integration Services: An Expert Cookbook
€37.99
SQL Server 2012 with PowerShell V3 Cookbook
€48.99
Total 135.97 Stars icon

Table of Contents

9 Chapters
Getting Started with SQL Server and PowerShell Chevron down icon Chevron up icon
SQL Server and PowerShell Basic Tasks Chevron down icon Chevron up icon
Basic Administration Chevron down icon Chevron up icon
Security Chevron down icon Chevron up icon
Advanced Administration Chevron down icon Chevron up icon
Backup and Restore Chevron down icon Chevron up icon
SQL Server Development Chevron down icon Chevron up icon
Business Intelligence Chevron down icon Chevron up icon
Helpful PowerShell Snippets Chevron down icon Chevron up icon

Customer reviews

Rating distribution
Full star icon Full star icon Full star icon Full star icon Half star icon 4.4
(5 Ratings)
5 star 80%
4 star 0%
3 star 0%
2 star 20%
1 star 0%
Parvinder Nijjar Aug 20, 2015
Full star icon Full star icon Full star icon Full star icon Full star icon 5
If your a SQL DBA with intermediate knowledge of Powershell then this is the ideal guide for you.
Amazon Verified review Amazon
Tony McBroom Aug 10, 2015
Full star icon Full star icon Full star icon Full star icon Full star icon 5
New to Powershell and this book is helping me immensely! Will update my review once I work my way through to the end, but it has been fantastic thus far...
Amazon Verified review Amazon
Mary Jane Zhang Jul 20, 2013
Full star icon Full star icon Full star icon Full star icon Full star icon 5
I wanted to learn how to use PowerShell with SQL Server. This book delivers easy to read chapters and easy to follow exercises. I liked the clear and to-the-point examples and explanations. While not exhaustive of all SQL Server 2012 features, this book provides a very good foundation to anyone who wants to start using PowerShell with SQL Server. It starts off with the basics, so even if you are not very familiar with PowerShell this book can get you started. Its inclusion of numerous SMO examples also bridge the short list of cmdlets available with the SQL Server product. You can take pieces from this book, and build your own complex automation solution!
Amazon Verified review Amazon
Scott Mattie Mar 29, 2013
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Donabel did an amazing job with this book. I liked the way she started out with a base and then quickly added to the foundation. She starts off with simple powershell commands, tips and tools and then slowly starts to add more knowledge. It is a must read.
Amazon Verified review Amazon
Denis M. McDowell Jun 04, 2013
Full star icon Full star icon Empty star icon Empty star icon Empty star icon 2
I bought this book as a reference for some SQL Server 2012 automation I am working on. While this book covers many of the day to day functions of a DBA, it leaves out virtually all of the new SQL 2012 features and how to manage them in PowerShell. Not a word about AlwaysOn Availability Groups, Contained DB, or other important features. I was disappointed that these items were left out. It is almost as if they simply changed "SQL Server 2008 R2" to "SQL Server 2012".
Amazon Verified review Amazon
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

How do I buy and download an eBook? Chevron down icon Chevron up icon

Where there is an eBook version of a title available, you can buy it from the book details for that title. Add either the standalone eBook or the eBook and print book bundle to your shopping cart. Your eBook will show in your cart as a product on its own. After completing checkout and payment in the normal way, you will receive your receipt on the screen containing a link to a personalised PDF download file. This link will remain active for 30 days. You can download backup copies of the file by logging in to your account at any time.

If you already have Adobe reader installed, then clicking on the link will download and open the PDF file directly. If you don't, then save the PDF file on your machine and download the Reader to view it.

Please Note: Packt eBooks are non-returnable and non-refundable.

Packt eBook and Licensing When you buy an eBook from Packt Publishing, completing your purchase means you accept the terms of our licence agreement. Please read the full text of the agreement. In it we have tried to balance the need for the ebook to be usable for you the reader with our needs to protect the rights of us as Publishers and of our authors. In summary, the agreement says:

  • You may make copies of your eBook for your own use onto any machine
  • You may not pass copies of the eBook on to anyone else
How can I make a purchase on your website? Chevron down icon Chevron up icon

If you want to purchase a video course, eBook or Bundle (Print+eBook) please follow below steps:

  1. Register on our website using your email address and the password.
  2. Search for the title by name or ISBN using the search option.
  3. Select the title you want to purchase.
  4. Choose the format you wish to purchase the title in; if you order the Print Book, you get a free eBook copy of the same title. 
  5. Proceed with the checkout process (payment to be made using Credit Card, Debit Cart, or PayPal)
Where can I access support around an eBook? Chevron down icon Chevron up icon
  • If you experience a problem with using or installing Adobe Reader, the contact Adobe directly.
  • To view the errata for the book, see www.packtpub.com/support and view the pages for the title you have.
  • To view your account details or to download a new copy of the book go to www.packtpub.com/account
  • To contact us directly if a problem is not resolved, use www.packtpub.com/contact-us
What eBook formats do Packt support? Chevron down icon Chevron up icon

Our eBooks are currently available in a variety of formats such as PDF and ePubs. In the future, this may well change with trends and development in technology, but please note that our PDFs are not Adobe eBook Reader format, which has greater restrictions on security.

You will need to use Adobe Reader v9 or later in order to read Packt's PDF eBooks.

What are the benefits of eBooks? Chevron down icon Chevron up icon
  • You can get the information you need immediately
  • You can easily take them with you on a laptop
  • You can download them an unlimited number of times
  • You can print them out
  • They are copy-paste enabled
  • They are searchable
  • There is no password protection
  • They are lower price than print
  • They save resources and space
What is an eBook? Chevron down icon Chevron up icon

Packt eBooks are a complete electronic version of the print edition, available in PDF and ePub formats. Every piece of content down to the page numbering is the same. Because we save the costs of printing and shipping the book to you, we are able to offer eBooks at a lower cost than print editions.

When you have purchased an eBook, simply login to your account and click on the link in Your Download Area. We recommend you saving the file to your hard drive before opening it.

For optimal viewing of our eBooks, we recommend you download and install the free Adobe Reader version 9.