Click to Rate and Give Feedback
MSDN
MSDN Library
SQL Server
SQL Server 2008 R2
Database Engine
Development
Scripting
 Running SQL Server PowerShell
Community Content
In this section
Statistics Annotations (7)
Collapse All/Expand All Collapse All
Running SQL Server PowerShell

SQL Server installs Windows PowerShell and a set of SQL Server snap-ins that expose SQL Server functionality in Windows PowerShell. You can then code Windows PowerShell scripts that work with SQL Server objects. The scripts can be run in the Windows PowerShell environment, in SQL Server Management Studio, and as SQL Server Agent jobs.

You install the software required to run Windows PowerShell scripts by using SQL Server Setup. Beginning in SQL Server 2008, Setup installs the following Windows PowerShell components when you select either the client software or the Database Services nodes:

  • Windows PowerShell 1.0, if Windows PowerShell is not already present on your computer.

  • The SQL Server snap-ins. The snap-ins are dll files that implement two types of Windows PowerShell support for SQL Server:

    • A set of SQL Server cmdlets. Cmdlets are commands that implement a specific action. For example, Invoke-Sqlcmd runs a Transact-SQL or XQuery script that can also be run by using the sqlcmd utility, and Invoke-PolicyEvaluation reports whether SQL Server objects comply with policy-based management policies.

    • A SQL Server provider. The provider lets you navigate the hierarchy of SQL Server objects using a path similar to a file system path. Each object is associated with a class from the SQL Server Management object models. You can use the methods and properties of the class to perform work on the objects. For example, if you cd to a databases object in a path, you can use the methods and properties of the Microsoft.SqlServer.Managment.SMO.Database class to manage the database.

  • The sqlps utility that is used to run Windows PowerShell sessions that include the SQL Server snap-ins.

Beginning in SQL Server 2008, SQL Server Management Studio supports starting Windows PowerShell sessions from the Object Explorer tree. Also beginning in SQL Server 2008, SQL Server Agent supports Windows PowerShell job steps.

If Windows PowerShell is uninstalled after Setup finishes, the SQL Server features for Windows PowerShell will not function. Windows PowerShell can be uninstalled by Windows users, and uninstalling Windows PowerShell might be required by some Windows operating system upgrades. If Windows PowerShell has been uninstalled and you want to use the SQL Server features, you must do one of the following:

  • Manually download and reinstall Windows PowerShell 1.0 from the Microsoft Download Center. Download instructions are on the Windows Server 2003 Web site.

  • If you are running Windows Server 2008, Windows PowerShell 1.0 exists in the operating system but is disabled by default. You can re-enable Windows PowerShell from Windows Server 2008.

You must use the SQL Server 2008 client components to run Windows PowerShell. Windows PowerShell can connect to instances of SQL Server 2000 or later. The earliest version of SQL Server 2005 that you can use is SP2. The earliest version of SQL Server 2000 that you can use is SP4. When Windows PowerShell connects to SQL Server 2005 and SQL Server 2000, it is limited to the functionality available in those versions of SQL Server.

sqlps is a utility that creates a Windows PowerShell environment and then loads and registers the SQL Server snap-ins. You can use sqlps to:

  • Interactively run Windows PowerShell commands.

  • Run Windows PowerShell script files.

  • Run SQL Server cmdlets.

  • Use the SQL Server provider paths to navigate through the hierarchy of SQL Server objects.

By default, sqlps runs with the scripting execution policy set to Restricted, which prevents running any Windows PowerShell scripts. You can use the Set-ExecutionPolicy cmdlet to enable running signed scripts, or any scripts. Only run scripts from trusted sources, and secure all input and output files using the appropriate NTFS permissions. For more information about enabling Windows PowerShell scripts, see Running Windows PowerShell Scripts.

For more information, see sqlps Utility.

You can start Windows PowerShell sessions in SQL Server Management Studio by right-clicking objects in Object Explorer and selecting Start PowerShell. SQL Server Management Studio then starts a Windows PowerShell session in which the SQL Server PowerShell snap-ins have been loaded and registered. The path for the session is preset to the location of the object you right clicked in Object Explorer. For example, if you right-click the AdventureWorks2008R2 database object in Object Explorer and select Start PowerShell, the Windows PowerShell path is set to the following:

SQLSERVER:\SQL\MyComputer\MyInstance\Databases\AdventureWorks2008R2>

There are several types of SQL Server Agent job steps. Each type is associated with a subsystem that implements a specific environment, such as a replication agent or command prompt environment. The SQL Server Agent subsystem for Windows PowerShell supports job steps that execute Windows PowerShell scripts. You can code Windows PowerShell scripts, and then use SQL Server Agent to include the scripts in jobs that run at scheduled times or in response to SQL Server events. The SQL Server Agent subsystem loads and registers the SQL Server snap-ins so that you can run Windows PowerShell scripts.

For more information, see SQL Server Agent Subsystems.

Caution noteCaution

Each SQL Server Agent job step launches a sqlps process which consumes approximately 20 MB of memory. Running large numbers of concurrent Windows PowerShell job steps can adversely impact performance.

The sqlps utility is a Windows PowerShell mini-shell. Mini-shells have certain restrictions. For example, they are coded to load in one or more Windows PowerShell snap-ins, but users and scripts cannot add other snap-ins. If you require functionality not supported by a mini-shell, such as working with both the SQL Server snap-ins and the snap-ins from another product, you can add the SQL Server snap-ins directly into a Windows PowerShell environment.

Paste the following code into Notepad and save it as a ps1 script file on your computer, such as C:\MyFolder\InitializeSQLProvider.ps1:

#
# Add the SQL Server Provider.
#

$ErrorActionPreference = "Stop"

$sqlpsreg="HKLM:\SOFTWARE\Microsoft\PowerShell\1\ShellIds\Microsoft.SqlServer.Management.PowerShell.sqlps"

if (Get-ChildItem $sqlpsreg -ErrorAction "SilentlyContinue")
{
    throw "SQL Server Provider for Windows PowerShell is not installed."
}
else
{
    $item = Get-ItemProperty $sqlpsreg
    $sqlpsPath = [System.IO.Path]::GetDirectoryName($item.Path)
}


#
# Set mandatory variables for the SQL Server provider
#
Set-Variable -scope Global -name SqlServerMaximumChildItems -Value 0
Set-Variable -scope Global -name SqlServerConnectionTimeout -Value 30
Set-Variable -scope Global -name SqlServerIncludeSystemObjects -Value $false
Set-Variable -scope Global -name SqlServerMaximumTabCompletion -Value 1000

#
# Load the snapins, type data, format data
#
Push-Location
cd $sqlpsPath
Add-PSSnapin SqlServerCmdletSnapin100
Add-PSSnapin SqlServerProviderSnapin100
Update-TypeData -PrependPath SQLProvider.Types.ps1xml 
update-FormatData -prependpath SQLProvider.Format.ps1xml 
Pop-Location

You can then use the script to launch the Windows PowerShell environment in which the SQL Server snap-ins are loaded by using this command:

PowerShell -NoExit -Command "C:\MyFolder\InitializeSQLProvider.ps1"

The command can be run at a command prompt, from a desktop shortcut, or from the Run dialog box in the Start menu. By default, Windows PowerShell runs in Restricted mode, which does not support running scripts. For more information about enabling Windows PowerShell scripts, see Running Windows PowerShell Scripts.

The SQL Server provider automatically loads the SQL Server Management Object (SMO) assemblies. There are two cases where you may need to load the SMO assemblies directly:

  • If your script references a SMO object before the first command that references the provider or cmdlets from the SQL Server snap-ins.

  • You want to port SMO code from another language, such as C# or VB.Net, that does not use the provider or cmdlets.

The following code loads the SMO assemblies:

#
# Loads the SQL Server Management Objects (SMO)
#

$ErrorActionPreference = "Stop"

$sqlpsreg="HKLM:\SOFTWARE\Microsoft\PowerShell\1\ShellIds\Microsoft.SqlServer.Management.PowerShell.sqlps"

if (Get-ChildItem $sqlpsreg -ErrorAction "SilentlyContinue")
{
    throw "SQL Server Provider for Windows PowerShell is not installed."
}
else
{
    $item = Get-ItemProperty $sqlpsreg
    $sqlpsPath = [System.IO.Path]::GetDirectoryName($item.Path)
}


$assemblylist = 
"Microsoft.SqlServer.Management.Common",
"Microsoft.SqlServer.Smo",
"Microsoft.SqlServer.Dmf ",
"Microsoft.SqlServer.Instapi ",
"Microsoft.SqlServer.SqlWmiManagement ",
"Microsoft.SqlServer.ConnectionInfo ",
"Microsoft.SqlServer.SmoExtended ",
"Microsoft.SqlServer.SqlTDiagM ",
"Microsoft.SqlServer.SString ",
"Microsoft.SqlServer.Management.RegisteredServers ",
"Microsoft.SqlServer.Management.Sdk.Sfc ",
"Microsoft.SqlServer.SqlEnum ",
"Microsoft.SqlServer.RegSvrEnum ",
"Microsoft.SqlServer.WmiEnum ",
"Microsoft.SqlServer.ServiceBrokerEnum ",
"Microsoft.SqlServer.ConnectionInfoExtended ",
"Microsoft.SqlServer.Management.Collector ",
"Microsoft.SqlServer.Management.CollectorEnum",
"Microsoft.SqlServer.Management.Dac",
"Microsoft.SqlServer.Management.DacEnum",
"Microsoft.SqlServer.Management.Utility"


foreach ($asm in $assemblylist)
{
    $asm = [Reflection.Assembly]::LoadWithPartialName($asm)
}

Push-Location
cd $sqlpsPath
update-FormatData -prependpath SQLProvider.Format.ps1xml 
Pop-Location
Tags What's this?: Add a tag
Community Content   What is Community Content?
Add new content RSS  Annotations
Installation of Powershell for SQL      Sait Sadunoglu   |   Edit   |   Show History

How to installation and requirement follow this link http://www.microsoft.com/download/en/details.aspx?id=16978 (Microsoft® SQL Server® 2008 R2 Feature Pack) download

Installing follow packs;

  • Microsoft® Windows PowerShell Extensions for SQL Server® 2008 R2
  • Microsoft® SQL Server® 2008 R2 Shared Management Objects
  • Microsoft® Core XML Services (MSXML) 6.0 SP 1
  • Microsoft® SQL Server® 2008 R2 Native Client
  • Microsoft® System CLR Types for SQL Server® 2008 R2

bye

Sait Sadunoğlu

Tags What's this?: Add a tag
Flag as ContentBug
The list of assemblies in "Loading the SMO..." is incorrect      davidbaxterbrowne   |   Edit   |   Show History

Microsoft.SqlServer.Management.Common
Microsoft.SqlServer.Management.Dac
Microsoft.SqlServer.Management.DacEnum
Microsoft.SqlServer.Management.Utility

Should be removed, leaving


$assemblylist =
"Microsoft.SqlServer.Smo",
"Microsoft.SqlServer.Dmf ",
"Microsoft.SqlServer.Instapi ",
"Microsoft.SqlServer.SqlWmiManagement ",
"Microsoft.SqlServer.ConnectionInfo ",
"Microsoft.SqlServer.SmoExtended ",
"Microsoft.SqlServer.SqlTDiagM ",
"Microsoft.SqlServer.SString ",
"Microsoft.SqlServer.Management.RegisteredServers ",
"Microsoft.SqlServer.Management.Sdk.Sfc ",
"Microsoft.SqlServer.SqlEnum ",
"Microsoft.SqlServer.RegSvrEnum ",
"Microsoft.SqlServer.WmiEnum ",
"Microsoft.SqlServer.ServiceBrokerEnum ",
"Microsoft.SqlServer.ConnectionInfoExtended ",
"Microsoft.SqlServer.Management.Collector ",
"Microsoft.SqlServer.Management.CollectorEnum",

Tags What's this?: Add a tag
Flag as ContentBug
Bug in SMO loader script      Jim Harrison MSO Security   |   Edit   |   Show History
The SQL MO loader script generates the following error if you run it more than once (as you might during debugging):

Update-FormatData : There were errors in loading the format data file:
Microsoft.PowerShell, C:\Program Files (x86)\Microsoft SQL Server\100\Tools\Binn\SQLProvider.Format.ps1xml : File skipped because it was already present from "Microsoft.PowerShell".
Microsoft.PowerShell, C:\Program Files (x86)\Microsoft SQL Server\100\Tools\Binn\SQLProvider.Format.ps1xml : File skipped because it was already present from "Microsoft.PowerShell".

To fix this, replace
Push-Location
cd $SqlPsPath
Update-FormatData -PrependPath SQLProvider.Format.ps1xml
Pop-Location

..with:
$SqlFormat = Get-FormatData 'Microsoft.SqlServer.Management.*'
if(0 -eq $SqlFormat.Length)
{
Push-Location
cd $SqlPsPath
Update-FormatData -PrependPath SQLProvider.Format.ps1xml
Pop-Location
}
Tags What's this?: Add a tag
Flag as ContentBug
SQLPS available as a snap-in for SQL Server 2008 R2      Tom Mills Microsoft   |   Edit   |   Show History
For Windows Server 2008 R2 and SQL Server 2008 R2, SQLPS.exe is available as a snap-in.

Use the commands Add-PSSnapin SqlServerProviderSnapin and Add-PSSnapin SqlServerCmdletSnapin in your Powershell script to provide access to SQLPS cmdlets. Note that it may throw an error if the Add-PSSnapin command has already been run in your Powershell session.
Tags What's this?: Add a tag
Flag as ContentBug
Don't Press Tab!      brianary   |   Edit   |   Show History
Tab-completion, one of the major benefits of PowerShell (in terms of exploration as well as efficiency), is unusably slow and broken in sqlps.
Tags What's this?: Add a tag
Flag as ContentBug
Client tools required for SQL PowerShell      mosaic   |   Edit   |   Show History

In the paragraph "Installing SQL Server PowerShell Support", it is not clear what "the client software" refers to.
In the Feature Selection step of the installation there is no single checkbox for "client software". Here is a list of likely candidates:
Client Tools Connectivity
Client Tools Backwards Compatibility
Client Tools SDK
Management Tools - Basic
Management Tools - Complete
SQL Client Connectivity SDK
Redistributable Features
Which one of these is the minimum to get the two PowerShell snap-ins?

This does not work for Server 2008 R2 or SP2      mossguy   |   Edit   |   Show History
From what I can tell, you can not install Windows PowerShell Version 1 on Server 2008 R2 or SP2, as it errors saying that this update does not apply to your system. So even the SQL web installer platform will install PoSH v2. This causes the installation of SQL Management studio to fail, because it requires PoSH v1.

I can't believe I am the only person having this issue...??

I have a thread on Technet about it....
http://social.technet.microsoft.com/Forums/en-US/sqlexpress/thread/22125757-0a1b-490d-9ec8-dd46a6e89689
Tags What's this?: Add a tag
Flag as ContentBug
Processing
© 2012 Microsoft. All rights reserved. Terms of Use | Trademarks | Privacy Statement
Page view tracker