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

eBook
€8.99 €39.99
Paperback
€49.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 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 : 9781785283611
Vendor :
Microsoft
Category :
Languages :
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 : Dec 04, 2015
Length: 760 pages
Edition : 1st
Language : English
ISBN-13 : 9781785283611
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

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.