Vous êtes sur la page 1sur 1

Practical PowerShell For SQL Server Developers and DBAs

Download the latest version of this PowerShell wallchart and read the accompanying in-depth article
from Simple-Talk at http://bit.ly/MZmOX9

Profile Locations

Module Repositories

Store aliases and commands that you always want available.

Store your modulesincluding sqlpsin one of these.


system-level
user-level

all users and all shells


$env:windir\System32\WindowsPowerShell\v1.0\profile.ps1
all users and
$env:windir\System32\WindowsPowerShell\v1.0\ Microsoft.PowerShell_profile.ps1
Microsoft.PowerShell shell

$env:windir \System32\WindowsPowerShell\v1.0\Modules
$HOME \Documents\WindowsPowerShell\Modules

Modules vs. Snap-ins

current user and all shells $HOME\Documents\WindowsPowerShell\profile.ps1


current user and
$HOME\Documents\WindowsPowerShell\Microsoft.PowerShell_profile.ps1
Microsoft.PowerShell shell

Loading snap-ins for SQL support are deprecated, though available.


Cmdlet support
Provider support

SQL Server 2008 & 2008 R2


SQLServerCmdletSnapin100
SQLServerProviderSnapin100

SQL Server 2012


SQLServerCmdletSnapin110
SQLServerProviderSnapin110

Rather, use the sqlps module instead.


Modules
Snap-ins

Load
Import-Module
Add-PSSnapin

View items loaded


Get-Module
Get-PSSnapin

[-ServerInstance <PSObject>]
[-Database <String>]
[-EncryptConnection]
[-Username <String>]
[-Password <String>]
[[-Query] <String>]
[-QueryTimeout <Int32>]
[-ConnectionTimeout <Int32>]
[-ErrorLevel <Int32>]
[-SeverityLevel <Int32>]
[-MaxCharLength <Int32>]
[-MaxBinaryLength <Int32>]
[-AbortOnError]
[-DedicatedAdministratorConnection]
[-DisableVariables]
[-DisableCommands]
[-HostName <String>]
[-NewPassword <String>]
[-Variable <String[]>]
[-InputFile <String>]
[-OutputSqlErrors]
[-SuppressProviderConte xtWarning]
[-IgnoreProviderContext]
[<CommonParameters>]

Type specified in modulespecific formatting file?


Type specified in system
formatting file?
DefaultDisplayPropertySet
defined?

Format-verb cmdlet specified


in pipeline?
Type specified in modulespecific formatting file?
Type specified in system
formatting file?
More than four properties?

Description
SQL Server data store root
Network root
Instances on selected machine
Top-level instance objects
Databases in selected instance

Node
\
\SQL
\SQL\machine
\SQL\machine\instance
\SQL\machine\instance\Databases

Top-level DB objects

\SQL\machine\instance\Databases\database

Use Format-List; otherwise, use Format-Table

Default Properties
Name, Root, Description
MachineName
InstanceName
list of object names
Name, Status, RecoveryModel,
CompatLvl, Collation, Owner
list of object names

Object Type ( prefix = Microsoft.SqlServer.Management.)


....PowerShell.Extensions.SqlServerProviderExtension
....PowerShell.Extensions.Machine
....Smo.Server
System.String
....Smo.Database
System.String

- - - - Selected database nodes - - - Tables in selected database


Views in selected database
Roles in selected database
Triggers in selected database

\SQL\machine\instance\Databases\database\Tables
\SQL\machine\instance\Databases\database\Views
\SQL\machine\instance\Databases\database\Roles
\SQL\machine\instance\Databases\database\Triggers

Schema, Name, Created


Schema, Name, Created
Name
Name, Created

....Smo.Table
....Smo.View
....Smo.DatabaseRole
....Smo.Trigger

Top-level nodes: \SQL, \SQLPolicy, \SQLRegistration, \Utility, \DAC, \DataCollection, \IntegrationServices, \SQLAS
Database nodes: ApplicationRoles, Assemblies, AsymmetricKeys, Certificates, DatabaseAuditSpecifications, Defaults, ExtendedProperties, ExtendedStoredProcedures, FileGroups,
FullTextCatalogs, FullTextStopLists, LogFiles, PartitionFunctions, PartitionSchemes, PlanGuides, Roles, Rules, Schemas, ServiceBroker, StoredProcedures, SymmetricKeys, Synonyms,
Tables, Triggers, UserDefinedAggregates, UserDefinedDataTypes, UserDefinedFunctions, UserDefinedTableTypes, UserDefinedTypes, Users, Views, XmlSchemaCollections

Cmdlets implemented by SQL Server Provider

Command sequence
sql -Query select db_name()
sql -Query select db_name()-Server .\sqlexpress
sql -Query select * from clents| Out-GridView
sql select * from clents | Format-Table AutoSize
sql select * from clents | Format-List

Key Commands

Cmdlet
Get-Location
Set-Location
Get-ChildItem
Get-Item
Rename-Item
Remove-Item

Canonical
alias
gl
sl
gci
gi
rni
ri

Other aliases

Description

pwd
cd, chdir
dir, ls

Gets current node


Changes current node
Lists the objects at current node
Properties of current node
Renames an object
Removes an object

ren
del, erase, rd, rm, rmdir

Source: Navigate SQL Server PowerShell Paths on MSDN

For brevity sandboxDB aliases SQLSERVER:\SQL\machine\instance\databases\sandbox and gci


aliases Get-ChildItem.
Description

Command sequence

Go to root of SQL Server data store


Go to root of DB objects
List instance names on local machine
List databases on selected instance
List tables in selected database
List tables with shortcut, default properties
List subset of tables using SMO property
List tables,all properties

Set-Location SQLSERVER:\
Set-Location SQLSERVER:\SQL
Get-ChildItem SQLSERVER:\SQL\machine
Get-ChildItem SQLSERVER:\SQL\machine\instance\Databases
gci SQLSERVER:\SQL\machine\instance\Databases\database\Tables
gci sandboxDB:\Tables
gci sandboxDB:\Tables | where {$_.Schema -eq "dbo"}
gci sandboxDB:\Tables | Format-Table Force *

Scripting Tables or Complete Database


For brevity sandboxDB aliases SQLSERVER:\SQL\ machine\instance\databases\sandbox,
% aliases ForEach-Object, and ? aliases Where-Object.

Full database

| Format-List
| Format-Table
$env:windir\system32\ WindowsPowerShell \v1.0\Modules\*. format.ps1xml
$HOME\Documents\WindowsPowerShell\Modules\*.format.ps1xml
$env:windir\system32\ WindowsPowerShell \v1.0\*.format.ps1xml

Nodes in SQL Server Space

For brevity, sql aliases Invoke-Sqlcmd: New-Alias sql Invoke-Sqlcmd

Description
All tables (output to console)
All tables (output to file)
All tables (separate batches)
Selected tables
Single table
All tables with their indexes

Use $object.PSStandardMembers.DefaultDisplayPropertySet;
otherwise, display all properties

Nodes display either in PowerShells list format or table format automatically, unless you
explicitly specify otherwise.

Executing Queries
Description
Query with default context
Query specifying server
Query to interactive grid
Output in table format
Output in list format

$env:windir\system32\ WindowsPowerShell \v1.0\Modules\*. format.ps1xml


$HOME\Documents\WindowsPowerShell\Modules\*.format.ps1xml
$env:windir\system32\ WindowsPowerShell \v1.0\*.format.ps1xml

Determining List or Table Output

Copyright 2012 Michael Sorens


2012.07.02, Version 1.0.1
Published on Simple-Talk.com

Invoke-Sqlcmd

Nodes reveal only a portion of their properties by default; see Key Commands for more.

View items available to load


Get-Module -ListAvailable
Get-PSSnapin -Registered

Load sqlps module:


Import-Module sqlps DisableNameChecking

Executing Queries

Determining Default Properties

Command sequence
gci sandboxDB:\Tables | % { $_.Script() }
gci sandboxDB:\Tables | % { $_.Script() } | Set-Content C:\create.sql
gci sandboxDB:\Tables | % { $_.Script() + "GO" }
gci sandboxDB:\Tables | ? { $_.name -match "big.*" } | % { $_.Script() }
(gci sandboxDB:\Tables | ? { $_.name -eq "xyz_table" }).Script()
gci sandboxDB:\Tables | % {
$_.Script() + "GO"
$_.Indexes | % { $_.Script() + "GO" }
}
$myScriptFile = filepath
$myDbInstance = Get-Item nodepath
$mydb = $myDbInstance.Databases["dbName"]
$mydb.Script() | Out-File $myScriptFile
$scrp = new-object ('Microsoft.SqlServer.Management.Smo.Scripter') ($myDbInstance)
$scrp.Options.AppendToFile = $True
$scrp.Options.FileName = $myScriptFile
# Other options here
$scrp.Script([Microsoft.SqlServer.Management.Smo.SqlSmoObject[]]$mydb.Tables)

SQL Server drives


Use New-PSDrive to create drive shortcuts.
New-PSDrive Name DB PSProvider SQLSERVER
Root SQLSERVER:\sql\localhost\SQLEXPRESS\Databases
Get-PSDrive | ? { $_.Provider.Name -eq "SqlServer" } | select name,root
Name
---DB
SQLSERVER

Root
---SQLSERVER:\sql\localhost\SQLEXPRESS\Databases
SQLSERVER:\

References
Learning PowerShell, PowerShell in SQL Server 2012 / 2008,
SQL Server PowerShell Help, Using SQL Server Cmdlets

Key Terms
SMO

.NET classes to create applications that manage SQL


Server.

SQLPS

Module providing SQL Server support in PowerShell in


the form of new cmdlets (Invoke-Sqlcmd and others)
and a SQL Server provider.

SQL
Allows you to interact with the hierarchy of SQL Server
Server
objects just as a native PowerShell file system provider
Provider allows you to interact with files. You can navigate
through SQL Server space using paths to nodes
analogously to paths to files.
SQLPSX

CodePlex project introduced prior to sqlps to provide


SQL Server support in PowerShell, SQLPSX still provides
some functionality not covered by sqlps.

Vous aimerez peut-être aussi