SQL Server PowerShell provider—The PowerShell-specific extra functionality NOTE An added bonus is that you can install Management Studio by itself on either the serv-er or anothserv-er r
Trang 1Either during the initial installation of SQL 2008 or afterward while changing the installed
features, you are able to add the SQL Server–specific PowerShell features by using the setup
utility The Management Tools-Basic feature must be added, as shown in Figure 17.3
The Management Studio add-on is also required to get the PowerShell-specific features
installed This specific feature adds the following:
Management Studio—The graphical user interface for managing SQL Server 2008
SQLCMD—The utility that SQL scripters should already be familiar with
SQL Server PowerShell provider—The PowerShell-specific extra functionality
NOTE
An added bonus is that you can install Management Studio by itself on either the
serv-er or anothserv-er remote system, and be able to administserv-er your SQL Sserv-ervserv-er database
remotely Consideration should be given to whether the SQL Server is set up for remote
connections, and the appropriate firewall changes have been made to the network and
on the database server, if applicable
FIGURE 17.3 Installing the PowerShell features
Trang 2SQL Server PowerShell can be accessed in either of two ways:
You can open SQL Server PowerShell via the SQL Server Management Studio by
right-clicking on a particular object in the Object Explorer and selecting Start
PowerShell, as shown in Figure 17.4 This way is handy because it provides a prompt
in the SQL provider (which is discussed shortly) in the location of the object that
was right-clicked
You also can open SQL Server PowerShell directly from regular DOS or a regular
PowerShell console by simply navigating to the appropriate location, as shown in
Figure 17.5
FIGURE 17.4 Accessing PowerShell via SSMS
Trang 3NOTE
When you first open the shell, some errors may appear on the screen, which simply
indicates that PowerShell execution policy should be set This topic was covered near
the beginning of the chapter The execution policy for SQL Server PowerShell should
also be RemoteSigned, at least
SQL Server PowerShell
When you first get into SQL Server PowerShell, you might notice that this is a restricted
version of the default PowerShell console In other words, several of the core cmdlets are
not available in SQL Server PowerShell, and others might not work exactly the same
way For example, invoking the Get-Command cmdlet alone with no other arguments
does not list all the available commands
NOTE
Running Get-Command in SQL Server PowerShell without any parameters might
gener-ate the following message:
Get-Command : Object reference not set to an instance of an object
FIGURE 17.5 Accessing PowerShell using sqlps.exe.
Trang 4PS SQLSERVER:\>
NOTE
Profiles were discussed earlier in this chapter The SQL Server PowerShell minishell
also has its own profile, and you can manage it by simply typing notepad $profile in
SQL Server PowerShell A prompt may come up that the file cannot be found and
ask-ing whether it should be created
SQL Provider
Earlier in this chapter, the term provider was briefly introduced The SQL team decided to
implement a SQL Server provider What this provides is a layout of the SQL object
struc-ture, which resembles that of a regular file system
You use the SQL provider when accessing SQL Server PowerShell via SQL Server
Management Studio: depending on what object you right-click to access SQL Server
PowerShell, a prompt opens in the context of that particular object Basically, the way
certain commands work is also affected by the current location within the SQL Server
provider Here are two different examples of being placed in different locations within the
SQL Server provider In the first example, the AdventureWorks2008R2 database was
right-clicked within SSMS, as shown in Figure 17.6 In the second example, a specific table
(Person.Address) within the AdventureWorks2008R2 database was right-clicked, as shown
in Figure 17.7
When you start the SQL Server PowerShell minishell by simply invoking sqlps.exe as
seen earlier, a prompt opens at the root of the SQL Server provider
NOTE
Some of the core cmdlets like Get-Item, Remove-Item, and New-Item are typically
used within providers to retrieve, remove, and create items, respectively Within the
SQL Server provider, creating items using the New-Item cmdlet is currently not
support-ed Other methods are required to actually create items
Trang 5ptg FIGURE 17.6 SQL Server provider at the database level
FIGURE 17.7 SQL Server provider at the table level
NOTE
Four SQL-based providers are actually available in SQL Server 2008 and six in SQL
Server 2008 R2 We look only at the SQL provider that provides functionality for the
database engine itself in any detail in this chapter Refer to the SQL Server Books
Online documentation for more information on the other providers (SQLPolicy,
SQLRegistration, DataCollection, Utility, and DAC) The Utility and DAC providers are
available only in SQL Server 2008 R2
SQL Cmdlets
A number of cmdlets available in SQL Server PowerShell are part of the basic PowerShell
functionality However, within SQL Server PowerShell, five additional cmdlets are available
only after the minishell is started (or if the snap-in is loaded manually, which is not
covered in any detail here):
Invoke-PolicyEvaluation—A cmdlet that evaluates a SQL Server Policy-Based
Management policy (or policies) against a target server
Invoke-SqlCmd—A cmdlet that runs any regular T-SQL command and any
languages and commands supported by the sqlcmd utility, which may be more
familiar to most users
Trang 6NOTE
For more details on the three other cmdlets not discussed here, see the built-in help
for more information and examples
NOTE
The intent is to ship more cmdlets as part of SQL-PowerShell in the future after more
database users become more familiar with SQL Server PowerShell
SQL Server Agent Support
PowerShell has been integrated into the SQL Server Agent subsystem In other words, you
can create jobs that call PowerShell-specific commands to run
Consult SQL Server Books Online for more details on incorporating PowerShell into your
SQL Server Agent job steps
Step-By-Step Examples
The following sections provide examples of using PowerShell both for general tasks and
for SQL Server 2008–specific tasks We expand on some of the basic concepts introduced
earlier with SQL Server 2008–specific examples
General Tasks
Often you might be required to send out emails containing particular reports and/or
output from commands run
To do so, you use features from the NET Framework via PowerShell to send out emails, as
shown in here:
Function Send-Mail {
param([string]$To,[string]$From,[string]$Subject, `
Trang 7[string]$Body,[string]$File,[string]$SmtpServer)
If($SmtpServer -eq ““){
$SmtpServer = “FQDN of your SMTP server here”
}
$Smtp = New-Object System.Net.Mail.SMTPclient($SmtpServer)
$Message = New-Object
System.Net.Mail.MailMessage($From,$To,$Subject,$Body)
If ($File -ne ““) {
$Attach = New-Object System.Net.Mail.Attachment $File
$Message.Attachments.Add($Attach)
}
$smtp.Send($message)
}
You can enter the preceding code into a script or directly to the console If you type the
code in the console, you must press the Enter key twice (once to close the function and
another time on an empty line) before the PowerShell prompt returns
In the preceding code listing, functionality from the NET Framework is used to get SMTP
functionality A function is used so that this code could be easily copied as required into
new scripts, and so on Calling the function is then easy, and passing the command-line
arguments is shown here (the PowerShell prompt can vary depending on whether the
default PowerShell is used or the new SQL minishell):
PS>Send-Mail -To “end_user@user.com “ -From “user@user.com” –Subject
“Automated Email” -Body “Testing” -File “C:\reports\report.txt”
NOTE
You might need to configure some antivirus programs to allow the PowerShell.exe
process (or sqlps.exe) to “talk” over the SMTP protocol port (TCP 25)
Scheduling Scripts
From time to time, it may be useful to have a method to schedule PowerShell scripts to
run automatically based on a particular schedule (when the SQL Server Agent isn’t
avail-able locally, for example)
You can easily view the method to call PowerShell scripts by simply typing
powershell.exe /? from a PowerShell session, as shown here:
PS>powershell.exe /?
PowerShell -Command “& {Get-EventLog -LogName security}”
Trang 8
[Command {
-| <string> [ <command_parameters> ]
| <script_block> [ -args <argument_array> ] }
]
]
[ -Help | -?]
-NoLogo
Do not display the copyright banner on startup
-NoExit
Keep running after completing all startup commands
-NoProfile
Do not load a user profile
-OutputFormat
Format the output of all objects as either text strings (Text) or in a
serialized CLIXML format (XML)
-InputFormat
The input from stdin is formatted as either text strings (Text) or in a
serialized CLIXML format (XML)
-Command
sqlps runs the commands specified and then exits, unless -NoExit is also
specified Do not specify other characters after the -Command switch,
they will be read as command arguments
-Read input commands from the keyboard by using stdin
<string> [ <command_parameters> ]
Specifies a string containing the PowerShell commands to be run Use
the format “&{<command>}” The quotation marks identify a string and
the invocation operator (&) causes sqlps to run the command
<script_block> [ -args <argument_array> ]
Specifies a block of PowerShell commands to be run Use the format
{<script_block>}
-Help | -?
Show the syntax summary help
Trang 9NOTE
How do you know whether to use powershell.exe or sqlps.exe when scheduling
jobs? If you’re using anything relating to SMO and/or the SQL cmdlets in the script,
sqlps.exe would seem to be easier to use because all the prerequisites to using SMO
and the SQL cmdlets are already loaded, which can save several lines in a script As a
reminder, the SQL minishell is limited in its functionality, so powershell.exe may be
required in particular if you need to load some PowerShell functionality from another
application, such as Exchange
As discussed briefly earlier, SQL Server Agent can also be used to run scheduled PowerShell
commands
Common OS-Related Tasks
Now let’s look at some more OS-related tasks, while keeping our focus on SQL
Server–related tasks
Let’s check the status of the SQL Server service using the Get-Service cmdlet in the
regular PowerShell console:
PS>Get-Service “mssqlserver”
Status Name DisplayName
-
-Stopped MSSQLSERVER SQL Server (MSSQLSERVER)
PS>
NOTE
When multiple instances are in use, the service name is something like
MSSQL$INSTANCE01 To start such an instance from PowerShell or even the SQL
min-ishell, you would have to use the following syntax for the service name:
MSSQL`$INSTANCE01 The dollar sign ($) character is escaped so that PowerShell
does-n’t try to interpret this as the beginning of a variable when the string is parsed
The service is stopped When you use the pipeline feature of PowerShell, the service is
started:
PS>Get-Service “mssqlserver”|Start-Service
WARNING: Waiting for service ‘SQL Server (SQLSERVER)
Trang 10When you use Get-Service, a service object is retrieved When you use the pipeline, this
object is passed to Start-Service Start-Service is built to basically accept input from
the pipeline and autofills its parameters based on what was input; thus, it knows to start
the SQL Server service
NOTE
You could use SQL Server PowerShell, but because SQL Server wasn’t started,
Management Studio would not have been able to connect, and you could not open
SQL Server PowerShell by right-clicking You could use PowerShell to start sqlps.exe,
though, and then you could use the Get-Service and Start-Service cmdlets to
start SQL Server If you use SQL Server PowerShell by calling sqlps.exe directly from
within a default PowerShell console, the SQL Server could still be started, but a
con-nection wouldn’t be automatically made to the default instance of the database
Most administrators have probably already used the Windows Task Manager to look at the
SQL Server processes Perhaps it was to determine whether SQL seemed to be using too
much memory or some other issue PowerShell provides the Get-Process cmdlet, shown
here, to look at running processes:
PS>Get-Process sqlservr
Handles NPM(K) PM(K) WS(K) VM(M) CPU(s)
Id ProcessName
- - - -
-
-318 45 64156 44288 1554 2.03
572 sqlservr
PS>
Another common OS-related task is to look for events in the Windows application event
log:
PS>Get-EventLog Application -New 10
PS>Get-EventLog Application -New 10| `