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

SQL Server 2012 with PowerShell V3 Cookbook:

eBook
$9.99 $39.99
Paperback
$65.99
Subscription
Free Trial
Renews at $19.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 1. Getting Started with SQL Server and PowerShell

In this chapter, we will cover:

  • Working with the sample code

  • Exploring the SQL Server PowerShell hierarchy

  • Installing SMO

  • Loading SMO assemblies

  • Discovering SQL-related cmdlets and modules

  • Creating a SQL Server instance object

  • Exploring SMO Server objects

Introduction


PowerShell is an administrative tool that has both shell and scripting capabilities that can leverage Windows Management Instrumentation (WMI), COM components, and .NET libraries. PowerShell is becoming more prominent with each generation of Microsoft products. Support for it is being bundled, and improved, in a number of new and upcoming Microsoft product releases. Windows Server, Exchange, ActiveDirectory, SharePoint, and even SQL Server, have all shipped with added PowerShell support and cmdlets. Even vendors such as VMWare, Citrix, Cisco, and Quest, to name a few, have provided ways to allow their products to be accessible via PowerShell.

What makes PowerShell tick? Every systems administrator probably knows the pain of trying to integrate heterogeneous systems using some kind of scripting. Historically, the solution involved some kind of VBScript, some good old batch files, maybe some C# code, some Perl—you name it. Sysadmins either had to resort to duct taping different languages together to get things to work the way they intended, or just did not bother because of the complicated code.

This is where PowerShell comes in. One of the strongest points for PowerShell is that it simplifies automation and integration between different Microsoft ecosystems. As most products have support for PowerShell, getting one system to talk to another is just a matter of discovering what cmdlets, functions, or modules need to be pulled into the script. Even if the product does not have support yet for PowerShell, it most likely has .NET or COM support, which PowerShell can easily use.

Notable PowerShell V3 features

Some of the notable features in the latest PowerShell version are:

  • Workflows: PowerShell V3 introduces Windows PowerShell Workflow (PSWF), which as stated in MSDN (http://msdn.microsoft.com/en-us/library/jj134242.aspx):

    helps automate the distribution, orchestration, and completion of multi-computer tasks, freeing users and administrators to focus on higher-level tasks.

    PSWF leverages Windows Workflow Foundation 4.0 for the declarative framework, but using familiar PowerShell syntax and constructs.

  • Robust sessions: PowerShell V3 supports more robust sessions. Sessions can now be retained amid network interruptions. These sessions will remain open until they time out.

  • Scheduled jobs: There is an improved support for scheduled tasks. There are new cmdlets in the PSScheduledJob module that allow you to create, enable, and manage scheduled tasks.

  • Module AutoLoading: If you use a cmdlet that belongs to a module that hasn't been loaded yet, this will trigger PowerShell to search PSModulePath and load the first module that contains that cmdlet. This is something we can easily test:

    #check current modules in session
    Get-Module
    
    #use cmdlet from CimCmdlets module, which
    #is not loaded yet
    Get-CimInstance win32_bios 
    
    #note new module loaded CimCmdlets
    Get-Module 
    
    #use cmdlet from SQLPS module, which
    #is not loaded yet
    Invoke-Sqlcmd -Query "SELECT GETDATE()" -ServerInstance "KERRIGAN"
    
    #note new modules loaded SQLPS and SQLASCmdlets 
    Get-Module
  • Web service support: PowerShell V3 introduces the Invoke-WebRequest cmdlet, which sends HTTP or HTTPS requests to a web service and returns the object-based content that can easily be manipulated in PowerShell. You can think about downloading entire websites using PowerShell (and check out Lee Holmes' article on it: http://www.leeholmes.com/blog/2012/03/31/how-to-download-an-entire-wordpress-blog/).

  • Simplified language syntax: Writing your Where-Object and Foreach-Object has just become cleaner. Improvements in the language include supporting default parameter values, and simplified syntax.

    What you used to write in V1 and V2 with curly braces and $_ as follows:

    Get-Service | Where-Object { $_.Status -eq 'Running' }

    can now be rewritten in V3 as:

    Get-Service | Where-Object Status -eq 'Running'
  • Improved Integrated Scripting Environment (ISE): The new ISE comes with Intellisense, searchable commands in the sidebar, parameter forms, and live syntax checking.

Before you start: Working with SQL Server and PowerShell


Before we dive into the recipes, let's go over a few important concepts and terminologies that will help you understand how SQL Server and PowerShell can work together:

  • PSProvider and PSDrive: PowerShell allows different data stores to be accessed as if they are regular files and folders. PSProvider is similar to an adapter, which allows these data stores to be seen as drives.

    To get a list of the supported PSProvider objects, type:

    Get-PSProvider

    You should see something similar to the following screenshot:

    Depending on which instance of PSProvider is already available in your system, yours may be slightly different:

  • PSDrive: Think of your C:\, but for data stores other than the file system. To get a list of PSDrive objects in your system, type:

    Get-PSDrive

    You should see something similar to the following screenshot:

    Note that there is a PSDrive for SQLServer, which can be used to navigate, access, and manipulate SQL Server objects.

  • Execution policy: By default, PowerShell will abide by the current execution policy to determine what kind of scripts can be run. For our recipes, we are going to assume that you will run PowerShell as the administrator on your test environment. You will also need to set the execution policy to RemoteSigned :

    Set-ExecutionPolicy RemoteSigned

    This setting will allow PowerShell to run digitally-signed scripts, or local unsigned scripts.

  • Modules and snap-ins: Modules and snap-ins are ways to extend PowerShell. Both modules and snap-ins can add cmdlets and providers to your current session. Modules can additionally load functions, variables, aliases, and other tools to your session.

    Snap-ins are Dynamically Linked Libraries (DLL), and need to be registered before they can be used. Snap-ins are available in V1, V2, and V3. For example:

    Add-PSSnapin SqlServerCmdletSnapin100

    Modules, on the other hand, are more like your regular PowerShell .ps1 script files. Modules are available in V2 and V3. You do not need to register a module to use it, you just need to import:

    Import-Module SQLPS

    Note

    For more information on PowerShell basics, check out Appendix B, PowerShell Primer.

Working with the sample code


Samples in this book have been created and tested against SQL Server 2012 on Windows Server 2008 R2.

Note

To work with the sample code in this book using a similar VM setup that the book uses, see Appendix D, Creating a SQL Server VM.

How to do it...

If you want to use your current machine without creating a separate VM, as illustrated in Appendix D, Creating a SQL Server VM, follow these steps to prepare your machine:

  1. Install SQL Server 2012 on your current operating system—either Windows 7 or Windows Server 2008 R2. See the list of upported operating systems for SQL Server 2012:

    http://msdn.microsoft.com/en-us/library/ms143506.aspx

  2. Install PowerShell V3.

    • Although PowerShell V3 comes installed with Windows 8 and Windows Server 2012, at the time of writing this book these two operating systems are not listed in the list of operating systems that SQL Server 2012 supports.

    • To install PowerShell V3 on Windows 7 SP1, Windows Server 2008 SP2, or Windows Server 2008 R2 SP1:

      Install Microsoft .NET Framework 4.0, if it's not already there.

      Download and install Windows Management Framework 3.0, which contains PowerShell V3. At the time of writing this book, the Release Candidate (RC) is available from:

      http://www.microsoft.com/en-us/download/details.aspx?id=29939

  3. Enable PowerShell V3 ISE. We will be using the improved Integrated Scripting Environment in many samples in this book:

    • Right-click on Windows PowerShell on your taskbar and choose Run as Administrator.

    • Execute the following:

      PS C:\Users\Administrator>Import-Module ServerManager
PS C:\Users\Administrator>Add-WindowsFeature PowerShell-ISE
      
    • Test to ensure you can see and launch the ISE:

      PS C:\Users\Administrator> powershell_ise
      

      Alternatively you can go to Start | All Programs | Accessories | Windows PowerShell | Windows PowerShell ISE.

    • Set execution policy to RemoteSigned by executing the following, on the code editor:

      Set-ExecutionPolicy RemoteSigned

      Note

      If you want to run PowerShell V2 and V3 side by side, you can check out Jeffery Hicks' article, PowerShell 2 and 3, Side by Side:

      http://mcpmag.com/articles/2011/12/20/powershell-2-and-3-side-by-side.aspx

See also

Exploring the SQL Server PowerShell hierarchy


In SQL Server 2012, the original mini-shell has been deprecated, and SQLPS is now provided as a module. Launching PowerShell from SSMS now launches a Windows PowerShell session, imports the SQLPS module, and sets the current context to the item the PowerShell session was launched from. DBAs and developers can then start navigating the object hierarchy from here.

Getting ready

Log in to SQL Server 2012 Management Studio.

How to do it...

In this recipe, we will navigate the SQL Server PowerShell hierarchy by launching a PowerShell session from SQL Server Management Studio:

  1. Right-click on your instance node.

  2. Click on Start PowerShell. This will launch a PowerShell session and load the SQLPS module. This window looks similar to a command prompt, with a prompt set to the SQL Server object you launched this window from:

    Note the starting path in this window.

  3. Type dir. This should give you a list of all objects directly accessible from the current server instance—in our case, from the default SQL Server instance KERRIGAN. Note that dir is an alias for the cmdlet Get-ChildItem.

    This is similar to the objects you can find under the instance node in Object Explorer in SQL Server Management Studio.

  4. While our PowerShell window is open, let's explore the SQL Server PSDrive, or the SQL Server data store, which PowerShell treats as a series of items. Type cd\. This will change the path to the root of the current drive, which is our SQL Server PSDrive.

  5. Type dir. This will list all Items accessible from the root SQL Server PSDrive. You should see something similar to the following screenshot:

  6. Close this window.

  7. Go back to Management Studio, and right-click on one of your user databases.

  8. Click on Start PowerShell. Note that this will launch another PowerShell session, with a path that points to the database you right-clicked from:

    Note that the starting path of this window is different from the starting path when you first launched PowerShell in the second step. If you type dir from this location, you will see all items that are sitting underneath the AdventureWorks2008R2 database.

    You can see some of the items enumerated in this screen in SQL Server Management Studio's Object Explorer, if you expand the AdventureWorks2008R2 database node.

How it works...

When PowerShell is launched through Management Studio, a context-sensitive PowerShell session is created, which automatically loads the SQLPS module. This will be evident in the prompt, which by default shows the current path of the object from which the Start PowerShell menu item was clicked.

SQL Server 2008/2008 R2 was shipped with a SQLPS mini-shell, also referred to as SQLPS utility. This can also be launched from SSMS by right-clicking on an object from Object Explorer, and clicking on Start PowerShell. This mini-shell was designed to be a closed shell preloaded with SQL Server extensions. This shell was meant to be used for SQL Server only, which proved to be quite limiting because DBAs and developers often need to load additional snap-ins and modules in order to integrate SQL Server with other systems through PowerShell. The alternative way is to launch a full-fledged PowerShell session, and depending on your PowerShell version either load snap-ins or load the SQLPS module.

In SQL Server 2012, the original mini-shell has been deprecated. When you launch a PowerShell session from SSMS in SQL Server 2012, it launches the full-fledged PowerShell session, with the updated SQLPS module loaded by default.

SQL Server is exposed as a PowerShell drive (PSDrive), which allows for traversing of objects as if they are folders and files. Thus, familiar commands for traversing directories are supported in this provider, such as dir or ls. Note that these familiar commands are often just aliases to the real cmdlet name, in this case, Get-ChildItem.

When you launch PowerShell from Management Studio, you can immediately start navigating the SQL Server PowerShell hierarchy.

Installing SMO


SQL Server Management Objects (SMO) was introduced with SQL Server 2005 to allow SQL Server to be accessed and managed programmatically. SMO can be used in any .NET language, including C#, VB.NET, and PowerShell. SMO is the key to automating most SQL Server tasks. SMO is also backward compatible to previous versions of SQL Server, extending support all the way to SQL Server 2000.

SMO is comprised of two distinct classes: instance classes and utility classes.

Instance classes are the SQL Server objects. Properties of objects such as the server, the databases, and tables can be accessed and set using the instance classes.

Utility classes are helper or utility classes that accomplish common SQL Server tasks. These classes belong to one of three groups: Transfer class, Backup and Restore classes, or Scripter class.

To gain access to the SMO libraries, SMO needs to be installed, and the SQL Server-related assemblies need to be loaded.

Getting ready

There are a few ways to get SMO installed:

  • If you are installing SQL Server 2012, or already have SQL Server 2012, SMO can be installed by installing Client Tools SDK. Get your install disk or image ready.

  • If you want just SMO installed without installing SQL Server, download the SQL Server Feature 2012 pack.

How to do it...

If you are installing SQL Server or already have SQL Server:

  1. Load up your SQL Server install disk or image, and launch the setup.exe file.

  2. Select New SQL Server standalone installation or add features to an existing installation.

  3. Choose your installation type, and click on Next.

  4. In the Feature Selection window, make sure you select Client Tools SDK.

  5. Complete your installation.

After this, you should already have all the binaries needed to use SMO.

If you are not installing SQL Server, you must install SMO using the SQL Server Feature Pack on the machine you are using SMO with:

  1. Open your web browser, go to your favorite search engine, and search for SQL Server 2012 Feature Pack.

  2. Download the package.

  3. Double-click on SharedManagementObjects.msi to install.

There's more...

By default, the SMO assemblies will be installed in <SQL Server Install Directory>\110\SDK\Assemblies.

Loading SMO assemblies


Before you can use the SMO library, the assemblies need to be loaded. In SQL Server 2012, this step is easier than ever.

Getting ready

SQL Management Objects(SMO) must have already been installed on your machine.

How to do it...

In this recipe, we will load the SQLPS module.

  1. Open up your PowerShell console, or PowerShell ISE, or your favorite PowerShell editor.

  2. Type the import-module command as follows:

    Import-Module SQLPS
    
  3. Confirm that the module is loaded:

    Get-Module
    

How it works...

The way to load SMO assemblies has changed between different versions of PowerShell. In PowerShell v1, loading assemblies can be done explicitly using the Load() or LoadWithPartialName() methods. LoadWithPartialName() accepts the partial name of the assembly, and loads from the application directory or the Global Assembly Cache (GAC):

[void][Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.Smo")

Although LoadWithPartialName()is still supported and still remains a popular way of loading assemblies, this method should not be used because it will be deprecated in future versions.

Load() requires the fully qualified name of the assembly:

[void][Reflection.Assembly]::Load("Microsoft.SqlServer.Smo, Version=9.0.242.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91")

In PowerShell V2, assemblies can be added by using Add-Type:

Add-Type -AssemblyName "Microsoft.SqlServer.Smo"

In PowerShell V3, loading these assemblies one by one is no longer necessary as long as the SQLPS module is loaded:

Import-Module SQLPS

There may be cases where you will still want to load specific DLL versions if you are dealing with specific SQL Server versions. Or you may want to load only specific assemblies without loading the whole SQLPS module. In this case, the Add-Type command is still the viable method of bringing the assemblies in.

There's more...

When you import the SQLPS module, you might see an error about conflicting or unapproved verbs:

Note

The names of some imported commands from the module SQLPS include unapproved verbs that might make them less discoverable. To find the commands with unapproved verbs, run the Import-Module command again with the Verbose parameter. For a list of approved verbs, type Get-Verb.

This means there are some cmdlets that do not conform to the PowerShell naming convention, but the module and its containing cmdlets are still all loaded into your host. To suppress this warning, import the module with the –DisableNameChecking parameter.

See also

  • The Installing SMO recipe

Discovering SQL-related cmdlets and modules


In order to be effective at working with SQL Server and PowerShell, knowing how to explore and discover cmdlets, snap-ins, and modules is in order.

Getting ready

Log in to your SQL Server instance, and launch PowerShell ISE. If you prefer the console, you can also launch that instead.

How to do it...

In this recipe we will list the SQL-Server related commands and cmdlets.

  1. To discover SQL-related cmdlets, type the following in your PowerShell editor and run:

    #how many commands from modules that
    #have SQL in the name
    Get-Command -Module "*SQL*" | Measure-Object
    
    #list all the SQL-related commands
    Get-Command -Module "*SQL*" | 
    Select CommandType, Name, ModuleName | 
    Sort -Property ModuleName, CommandType, Name | 
    Format-Table -AutoSize

    After you execute the line, your output window should look similar to the following screenshot:

  2. To see which of these modules are loaded, type the following in your editor and run:

    Get-Module -Name "*SQL*"

    If you have already used any of the cmdlets in the previous step, then you should see both SQLPS and SQLASCMDLETS. Otherwise, you will need to load these modules before you can use them.

  3. To explicitly load these modules, type the following and run:

    Import-Module -Name "SQLPS"

    Note that SQLASCMDLETS will be loaded when you load SQLPS.

How it works...

At the core of PowerShell are cmdlets. A cmdlet (pronounced commandlet) can be a compiled, reusable .NET code, or an advanced function, or a workflow that typically performs a very specific task. All cmdlets follow the verb-noun naming notation.

PowerShell ships with many cmdlets and can be further extended if the shipped cmdlets are not sufficient for your purposes.

A legacy way of extending PowerShell is by registering additional snap-ins. A snap-in is a binary, or a DLL, that contains cmdlets. You can create your own by building your own .NET source, compiling, and registering the snap-in. You will always need to register snap-ins before you can use them. Snap-ins are a popular way of extending PowerShell.

The following table summarizes common tasks with snap-ins:

Task

Syntax

List loaded snap-ins

Get-PSSnapin

List installed snap-ins

Get-PSSnapin -Registered

Show commands in a snap-in

Get-Command -Module "SnapinName"

Load a specific snap-in

Add-PSSnapin "SnapinName"

When starting, PowerShell V2, modules are available as the improved and preferred method of extending PowerShell.

A module is a package that can contain cmdlets, providers, functions, variables, and aliases. In PowerShell V2, modules are not loaded by default, so required modules need to be explicitly imported.

Common tasks with modules are summarized in the following table:

Task

Syntax

List loaded modules

Get-Module

List installed modules

Get-Module -ListAvailable

Show commands in a module

Get-Command -Module "ModuleName"

Load a specific module

Import-Module -Name "ModuleName"

One of the improved features with PowerShell V3 is that it supports autoloading modules. You do not need to always explicitly load modules before using the contained cmdlets. Using the cmdlet in your script is enough to trigger PowerShell to load the module that contains it.

The SQL Server 2012 modules are located in the PowerShell/Modules folder of the Install directory:

There's more...

The following table shows the list of the SQLPS and SQLASCMDLETS cmdlets of this version:

CommandType Name

ModuleName

Cmdlet Add-RoleMember

SQLASCMDLETS

Cmdlet Backup-ASDatabase

SQLASCMDLETS

Cmdlet Invoke-ASCmd

SQLASCMDLETS

Cmdlet Invoke-ProcessCube

SQLASCMDLETS

Cmdlet Invoke-ProcessDimension

SQLASCMDLETS

Cmdlet Invoke-ProcessPartition

SQLASCMDLETS

Cmdlet Merge-Partition

SQLASCMDLETS

Cmdlet New-RestoreFolder

SQLASCMDLETS

Cmdlet New-RestoreLocation

SQLASCMDLETS

Cmdlet Remove-RoleMember

SQLASCMDLETS

Cmdlet Restore-ASDatabase

SQLASCMDLETS

Cmdlet Add-SqlAvailabilityDatabase

SQLPS

Cmdlet Add-SqlAvailabilityGroupListenerStaticIp

SQLPS

Cmdlet Backup-SqlDatabase

SQLPS

Cmdlet Convert-UrnToPath

SQLPS

Cmdlet Decode-SqlName

SQLPS

Cmdlet Disable-SqlHADRService

SQLPS

Cmdlet Enable-SqlHADRService

SQLPS

Cmdlet Encode-SqlName

SQLPS

Cmdlet Invoke-PolicyEvaluation

SQLPS

Cmdlet Invoke-Sqlcmd

SQLPS

Cmdlet Join-SqlAvailabilityGroup

SQLPS

Cmdlet New-SqlAvailabilityGroup

SQLPS

Cmdlet New-SqlAvailabilityGroupListener

SQLPS

Cmdlet New-SqlAvailabilityReplica

SQLPS

Cmdlet New-SqlHADREndpoint

SQLPS

Cmdlet Remove-SqlAvailabilityDatabase

SQLPS

Cmdlet Remove-SqlAvailabilityGroup

SQLPS

Cmdlet Remove-SqlAvailabilityReplica

SQLPS

Cmdlet Restore-SqlDatabase

SQLPS

Cmdlet Resume-SqlAvailabilityDatabase

SQLPS

Cmdlet Set-SqlAvailabilityGroup

SQLPS

Cmdlet Set-SqlAvailabilityGroupListener

SQLPS

Cmdlet Set-SqlAvailabilityReplica

SQLPS

Cmdlet Set-SqlHADREndpoint

SQLPS

Cmdlet Suspend-SqlAvailabilityDatabase

SQLPS

Cmdlet Switch-SqlAvailabilityGroup

SQLPS

Cmdlet Test-SqlAvailabilityGroup

SQLPS

Cmdlet Test-SqlAvailabilityReplica

SQLPS

Test-SqlDatabaseReplicaState

SQLPS

To learn more about these cmdlets, use the Get-Help cmdlet. For example:

Get-Help "Invoke-Sqlcmd" 
Get-Help "Invoke-Sqlcmd" -Detailed
Get-Help "Invoke-Sqlcmd" -Examples
Get-Help "Invoke-Sqlcmd" -Full

You can also check out the MSDN article on SQL Server database engine cmdlets:

http://msdn.microsoft.com/en-us/library/cc281847.aspx

When you load the SQLPS module, several assemblies are loaded into your host.

To get a list of SQL Server-related assemblies loaded with the SQLPS module, use the following script, which will work in both PowerShell V2 and V3:

Import-Module SQLPS –DisableNameChecking

[appdomain]::CurrentDomain.GetAssemblies() | 
Where {$_.FullName -match "SqlServer" } | 
Select FullName

If you want to run on a strictly V3 environment, you can take advantage of the simplified syntax:

Import-Module SQLPS –DisableNameChecking

[appdomain]::CurrentDomain.GetAssemblies() | 
Where FullName -match "SqlServer" | 
Select FullName

This will show you all the loaded assemblies, including their public key tokens:

More information on running PowerShell scripts

By default, PowerShell is running in restricted mode, in other words, it does not run scripts. To run our scripts from the book, we will set the execution policy to RemoteSigned as follows:

Set-ExecutionPolicy RemoteSigned

Note

See the Execution policy section in Appendix B, PowerShell Primer, for further explanation of different execution policies.

If you save your PowerShell code in a file, you need to ensure it has a .ps1 extension otherwise PowerShell will not run it. Ideally the filename you give your script does not have spaces. You can run this script from the PowerShell console simply by calling the name. For example if you have a script called myscript.ps1 located in the C:\ directory, this is how you would invoke it:

PS C:\> .\myscript.ps1

If the file or path to the file has spaces, then you will need to enclose the full path and file name in single or double quotes, and use the call (&) operator:

PS C:\>&'.\my script.ps1'

If you want to retain the variables and functions included in the script, in memory, thus making them available globally in your session, then you will need to dot source the script. To dot source is literally to prefix the filename, or the path to the file, with a dot and a space:

PS C:\> . .\myscript.ps1
PS C:\> . '.\my script.ps1'

More information on mixed assembly error

You may encounter an error when running some commands that are built using older .NET versions. Interestingly, you may see this while running your script in the PowerShell ISE, but not necessarily in the shell.

Invoke-Sqlcmd: Mixed mode assembly is built against version 'V2.0.50727' of the runtime and cannot be loaded in the 4.0 runtime without additional configuration information.

A few steps are required to solve this issue:

  1. Open Windows Explorer.

  2. Identify the Windows PowerShell ISE install folder path. You can find this out by going to Start | All Programs | Accessories | Windows | PowerShell, and then right-clicking on the Windows PowerShell ISE menu item and choosing Properties.

    For the 32-bit ISE, this is the default path:

    %windir%\sysWOW64\WindowsPowerShell\v1.0\PowerShell_ISE.exe

    For the 64-bit ISE, this is the default path:

    %windir%\system32\WindowsPowerShell\v1.0\PowerShell_ISE.exe

  3. Go to the PowerShell ISE Install folder.

  4. Create an empty file called powershell_ise.exe.config.

  5. Add the following snippet to the content and save the file:

    <?xml version="1.0" encoding="utf-8" ?>
    <configuration>
    <startup useLegacyV2RuntimeActivationPolicy="true">
    <supportedRuntime version="v4.0" />
    </startup>
    
    <runtime>
    <generatePublisherEvidence enabled="false" />
    </runtime>
    </configuration>
  6. Reopen PowerShell ISE and retry the command that failed.

Creating a SQL Server instance object


Most of what you will need to do in SQL Server will require a connection to an instance.

Getting ready

Open up your PowerShell console, the PowerShell ISE, or your favorite PowerShell editor.

You will need to note what your instance name is. If you have a default instance, you can use your machine name. If you have a named instance, the format will be <machine name>\<instance name>.

How to do it...

If you are connecting to your instance using Windows authentication, and using your current Windows login, follow these steps:

  1. Import the SQLPS module:

    #import SQLPS module
    Import-Module SQLPS –DisableNameChecking
  2. Store your instance name in a variable as follows:

    #create a variable for your instance name
    $instanceName = "KERRIGAN"
  3. If you are connecting to your instance using Windows authentication using the account you are logged in as:

    #create your server instance
    $server = New-Object -TypeName Microsoft.SqlServer.Management.Smo.Server -ArgumentList $instanceName

    If you are connecting using SQL Authentication, you will need to know the username and password that you will use to authenticate. In this case, you will need to add the following code, which will set the connection to mixed mode and prompt for the username and password:

    #set connection to mixed mode
    $server.ConnectionContext.set_LoginSecure($false)
    #set the login name
    #of course we don't want to hardcode credentials here
    #so we will prompt the user
    #note password is passed as a SecureString type
    $credentials = Get-Credential
    #remove leading backslash in username
    $login = $credentials.UserName -replace("\\", "")
    $server.ConnectionContext.set_Login($login) 
    $server.ConnectionContext.set_SecurePassword($credentials.Password)
    
    #check connection string
    $server.ConnectionContext.ConnectionString
    
    Write-Verbose "Connected to $($server.Name)"
    Write-Verbose "Logged in as $($server.ConnectionContext.TrueLogin)"

How it works...

Before you can access or manipulate SQL Server programmatically, you will often need to create references to its objects. At the most basic is the server.

The server instance uses the type Microsoft.SqlServer.Management.Smo.Server. By default, connections to the server are made using trusted connections, meaning it uses the Windows account you're currently using when you log into the server. So all it needs is the instance name in its argument list:

#create your server instance
$server = New-Object -TypeName Microsoft.SqlServer.Management.Smo.Server -ArgumentList $instanceName

If, however, you need to connect using a SQL login, you will need to set the ConnectionContext.LoginSecure property of the SMO Server class setting to false:

#set connection to mixed mode
$server.ConnectionContext.set_LoginSecure($false)

You will also need to explicitly set the username and the password. The best way to accomplish this is to prompt the user for the credentials.

#prompt
$credentials = Get-Credential

The credential window will capture the login and password. The Get-Credential cmdlet returns the username with a leading backslash if the domain is not specified. In this case, we want to remove this leading backslash.

#remove leading backslash in username
$login = $credentials.UserName -replace("\\","")

Once we have the login, we can pass it to the set_Login method. The password is already a SecureString type, which is what the set_SecurePassword expects, so we can readily pass this to the method:

$server.ConnectionContext.set_Login($login)
$server.ConnectionContext.set_SecurePassword($credentials.Password)

Should you want to hardcode the username and just prompt for the password, you can also do this:

$login="belle"

#prompt
$credentials = Get-Credential –Credential $login

In the script, you will also notice we are using Write-Verbose instead of Write-Host to display our results. This is because we want to be able to control the output without needing to always go back to our script and remove all the Write-Host commands.

By default, the script will not display any output, that is, the $VerbosePreference special variable is set to SilentlyContinue. If you want to run the script in verbose mode, you simply need to add this line in the beginning of your script:

$VerbosePreference = "Continue"

When you are done, you just need to revert the value to SilentlyContinue:

$VerbosePreference = "SilentlyContinue"

See also

  • The Loading SMO assemblies recipe

  • The Creating SQL Server instance using SMO recipe

Exploring SMO server objects


SQL Management Objects (SMO) comes with a hierarchy of objects that are accessible programmatically. For example, when we create an SMO server variable, we can then access databases, logins, and database-level triggers. Once we get a handle of individual databases, we can then traverse the tables, stored procedures, and views that it contains. Since many tasks involve SMO objects, you will be at an advantage if you know how to discover and navigate these objects.

Getting ready

Open up your PowerShell console, the PowerShell ISE, or your favorite PowerShell editor.

You will also need to note what your instance name is. If you have a default instance, you can use your machine name. If you have a named instance, the format will be <machine name>\<instance name>

How to do it...

In this recipe, we will start exploring the hierarchy of objects with SMO.

  1. Import the SQLPS module as follows:

    Import-Module SQLPS -DisableNameChecking
  2. Create a server instance as follows:

    $instanceName = "KERRIGAN"
    
    $server = New-Object `
            -TypeName Microsoft.SqlServer.Management.Smo.Server `
            -ArgumentList $instanceName
  3. Get the SMO objects directly accessible from the $server object:

    $server | 
    Get-Member -MemberType "Property" | 
    Where Definition -like "*Smo*"
  4. Now let's check SMO objects under databases. Execute the following line:

    $server.Databases | 
    Get-Member -MemberType "Property" | 
    Where Definition -like "*Smo*"
  5. To check out the tables, you can type and execute:

    $server.Databases["AdventureWorks2008R2"].Tables | 
    Get-Member -MemberType "Property" | 
    Where Definition -like "*Smo*"

How it works...

SMO contains a hierarchy of objects. At the very top there is a server object, which in turn contains objects such as Databases, Configuration, SqlMail, LoginCollection, and the like. These objects in turn contain other objects, for example, Databases is a collection that contains Database objects, and a Database in turn, contains Tables and so on.

See also

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
$19.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
$199.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
$279.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 $ 180.97
SQL Server 2012 with PowerShell V3 Cookbook
$65.99
Microsoft SQL Server 2012 Integration Services: An Expert Cookbook
$48.99
Microsoft SQL Server 2012 Performance Tuning Cookbook
$65.99
Total $ 180.97 Stars icon
Banner background image

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.