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 Print?

Product feature icon Instant access to your digital eBook copy whilst your Print order is Shipped
Product feature icon Paperback book shipped to your preferred address
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

Shipping Address

Billing Address

Shipping Methods
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
Estimated delivery fee Deliver to Latvia

Premium delivery 7 - 10 business days

€25.95
(Includes tracking information)

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 Print?

Product feature icon Instant access to your digital eBook copy whilst your Print order is Shipped
Product feature icon Paperback book shipped to your preferred address
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

Shipping Address

Billing Address

Shipping Methods
Estimated delivery fee Deliver to Latvia

Premium delivery 7 - 10 business days

€25.95
(Includes tracking information)

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 the delivery time and cost of print book? Chevron down icon Chevron up icon

Shipping Details

USA:

'

Economy: Delivery to most addresses in the US within 10-15 business days

Premium: Trackable Delivery to most addresses in the US within 3-8 business days

UK:

Economy: Delivery to most addresses in the U.K. within 7-9 business days.
Shipments are not trackable

Premium: Trackable delivery to most addresses in the U.K. within 3-4 business days!
Add one extra business day for deliveries to Northern Ireland and Scottish Highlands and islands

EU:

Premium: Trackable delivery to most EU destinations within 4-9 business days.

Australia:

Economy: Can deliver to P. O. Boxes and private residences.
Trackable service with delivery to addresses in Australia only.
Delivery time ranges from 7-9 business days for VIC and 8-10 business days for Interstate metro
Delivery time is up to 15 business days for remote areas of WA, NT & QLD.

Premium: Delivery to addresses in Australia only
Trackable delivery to most P. O. Boxes and private residences in Australia within 4-5 days based on the distance to a destination following dispatch.

India:

Premium: Delivery to most Indian addresses within 5-6 business days

Rest of the World:

Premium: Countries in the American continent: Trackable delivery to most countries within 4-7 business days

Asia:

Premium: Delivery to most Asian addresses within 5-9 business days

Disclaimer:
All orders received before 5 PM U.K time would start printing from the next business day. So the estimated delivery times start from the next day as well. Orders received after 5 PM U.K time (in our internal systems) on a business day or anytime on the weekend will begin printing the second to next business day. For example, an order placed at 11 AM today will begin printing tomorrow, whereas an order placed at 9 PM tonight will begin printing the day after tomorrow.


Unfortunately, due to several restrictions, we are unable to ship to the following countries:

  1. Afghanistan
  2. American Samoa
  3. Belarus
  4. Brunei Darussalam
  5. Central African Republic
  6. The Democratic Republic of Congo
  7. Eritrea
  8. Guinea-bissau
  9. Iran
  10. Lebanon
  11. Libiya Arab Jamahriya
  12. Somalia
  13. Sudan
  14. Russian Federation
  15. Syrian Arab Republic
  16. Ukraine
  17. Venezuela
What is custom duty/charge? Chevron down icon Chevron up icon

Customs duty are charges levied on goods when they cross international borders. It is a tax that is imposed on imported goods. These duties are charged by special authorities and bodies created by local governments and are meant to protect local industries, economies, and businesses.

Do I have to pay customs charges for the print book order? Chevron down icon Chevron up icon

The orders shipped to the countries that are listed under EU27 will not bear custom charges. They are paid by Packt as part of the order.

List of EU27 countries: www.gov.uk/eu-eea:

A custom duty or localized taxes may be applicable on the shipment and would be charged by the recipient country outside of the EU27 which should be paid by the customer and these duties are not included in the shipping charges been charged on the order.

How do I know my custom duty charges? Chevron down icon Chevron up icon

The amount of duty payable varies greatly depending on the imported goods, the country of origin and several other factors like the total invoice amount or dimensions like weight, and other such criteria applicable in your country.

For example:

  • If you live in Mexico, and the declared value of your ordered items is over $ 50, for you to receive a package, you will have to pay additional import tax of 19% which will be $ 9.50 to the courier service.
  • Whereas if you live in Turkey, and the declared value of your ordered items is over € 22, for you to receive a package, you will have to pay additional import tax of 18% which will be € 3.96 to the courier service.
How can I cancel my order? Chevron down icon Chevron up icon

Cancellation Policy for Published Printed Books:

You can cancel any order within 1 hour of placing the order. Simply contact customercare@packt.com with your order details or payment transaction id. If your order has already started the shipment process, we will do our best to stop it. However, if it is already on the way to you then when you receive it, you can contact us at customercare@packt.com using the returns and refund process.

Please understand that Packt Publishing cannot provide refunds or cancel any order except for the cases described in our Return Policy (i.e. Packt Publishing agrees to replace your printed book because it arrives damaged or material defect in book), Packt Publishing will not accept returns.

What is your returns and refunds policy? Chevron down icon Chevron up icon

Return Policy:

We want you to be happy with your purchase from Packtpub.com. We will not hassle you with returning print books to us. If the print book you receive from us is incorrect, damaged, doesn't work or is unacceptably late, please contact Customer Relations Team on customercare@packt.com with the order number and issue details as explained below:

  1. If you ordered (eBook, Video or Print Book) incorrectly or accidentally, please contact Customer Relations Team on customercare@packt.com within one hour of placing the order and we will replace/refund you the item cost.
  2. Sadly, if your eBook or Video file is faulty or a fault occurs during the eBook or Video being made available to you, i.e. during download then you should contact Customer Relations Team within 14 days of purchase on customercare@packt.com who will be able to resolve this issue for you.
  3. You will have a choice of replacement or refund of the problem items.(damaged, defective or incorrect)
  4. Once Customer Care Team confirms that you will be refunded, you should receive the refund within 10 to 12 working days.
  5. If you are only requesting a refund of one book from a multiple order, then we will refund you the appropriate single item.
  6. Where the items were shipped under a free shipping offer, there will be no shipping costs to refund.

On the off chance your printed book arrives damaged, with book material defect, contact our Customer Relation Team on customercare@packt.com within 14 days of receipt of the book with appropriate evidence of damage and we will work with you to secure a replacement copy, if necessary. Please note that each printed book you order from us is individually made by Packt's professional book-printing partner which is on a print-on-demand basis.

What tax is charged? Chevron down icon Chevron up icon

Currently, no tax is charged on the purchase of any print book (subject to change based on the laws and regulations). A localized VAT fee is charged only to our European and UK customers on eBooks, Video and subscriptions that they buy. GST is charged to Indian customers for eBooks and video purchases.

What payment methods can I use? Chevron down icon Chevron up icon

You can pay with the following card types:

  1. Visa Debit
  2. Visa Credit
  3. MasterCard
  4. PayPal
What is the delivery time and cost of print books? Chevron down icon Chevron up icon

Shipping Details

USA:

'

Economy: Delivery to most addresses in the US within 10-15 business days

Premium: Trackable Delivery to most addresses in the US within 3-8 business days

UK:

Economy: Delivery to most addresses in the U.K. within 7-9 business days.
Shipments are not trackable

Premium: Trackable delivery to most addresses in the U.K. within 3-4 business days!
Add one extra business day for deliveries to Northern Ireland and Scottish Highlands and islands

EU:

Premium: Trackable delivery to most EU destinations within 4-9 business days.

Australia:

Economy: Can deliver to P. O. Boxes and private residences.
Trackable service with delivery to addresses in Australia only.
Delivery time ranges from 7-9 business days for VIC and 8-10 business days for Interstate metro
Delivery time is up to 15 business days for remote areas of WA, NT & QLD.

Premium: Delivery to addresses in Australia only
Trackable delivery to most P. O. Boxes and private residences in Australia within 4-5 days based on the distance to a destination following dispatch.

India:

Premium: Delivery to most Indian addresses within 5-6 business days

Rest of the World:

Premium: Countries in the American continent: Trackable delivery to most countries within 4-7 business days

Asia:

Premium: Delivery to most Asian addresses within 5-9 business days

Disclaimer:
All orders received before 5 PM U.K time would start printing from the next business day. So the estimated delivery times start from the next day as well. Orders received after 5 PM U.K time (in our internal systems) on a business day or anytime on the weekend will begin printing the second to next business day. For example, an order placed at 11 AM today will begin printing tomorrow, whereas an order placed at 9 PM tonight will begin printing the day after tomorrow.


Unfortunately, due to several restrictions, we are unable to ship to the following countries:

  1. Afghanistan
  2. American Samoa
  3. Belarus
  4. Brunei Darussalam
  5. Central African Republic
  6. The Democratic Republic of Congo
  7. Eritrea
  8. Guinea-bissau
  9. Iran
  10. Lebanon
  11. Libiya Arab Jamahriya
  12. Somalia
  13. Sudan
  14. Russian Federation
  15. Syrian Arab Republic
  16. Ukraine
  17. Venezuela