Tải bản đầy đủ (.pdf) (10 trang)

Microsoft SQL Server 2008 R2 Unleashed- P55 pot

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (432.32 KB, 10 trang )

ptg
484
CHAPTER 17 Administering SQL Server 2008 with PowerShell
. Provider—Using this PowerShell functionality, a data store is presented to the user
in a format similar to a file system. Some of the “core” cmdlets are typically used to
do various tasks such as creating items like files and/or folders.
. Snap-in—PowerShell functionality can be extended with the use of snap-ins. They
are basically DLL files written in a .NET programming language such as C# or
VB.NET. DBAs can load these snap-ins in their PowerShell session to add additional
functionality such as additional cmdlets and/or providers.
. Tab completion—This PowerShell functionality allows the user to press the Tab key
to autocomplete supported commands and parameters.
. Aliases—Theseare shorter names that can be used for cmdlets. For example, some
typical UNIX and DOS commands have had aliases for them created in PowerShell.
These aliases map to the actual PowerShell cmdlet.
Object-Based Functionality
As mentioned earlier, PowerShell is built on the .NET Framework. This implies that every-
thing within PowerShell is object based. This is a familiar concept for anyone who is already
familiar with the .NET Framework or .NET programming languages such as C# or VB.NET.
This object-based functionality is an important concept to remember if you want to dive
deeper into PowerShell. PowerShell provides many features, and it can also use additional
features provided by other .NET assemblies.
SQL Server Management Objects
SQL Server Management Objects (SMO) are a very useful tool to advanced users and devel-
opers when dealing with the automation of SQL Server 2005 and 2008. A lot of the
features within SQL Server (core engine, agent, mail, and so on) are packaged into easy-to-
access .NET libraries that can be accessed from PowerShell.
Most of the functionality provided by the new PowerShell support in SQL 2008 is based
on SMO.
As for SQL Server 2005, PowerShell can still be used to administer this version via SMO.
The only difference is that the relevant assemblies must be loaded manually.


WMI
Windows Management Instrumentation (WMI) is a Windows service that provides remote
control and management. PowerShell provides some built-in support for retrieving infor-
mation via WMI.
Although the main goal of WMI may be to provide remote access, it can also be used
locally and can provide a wealth of information about a system. For example, WMI can be
Download from www.wowebook.com
ptg
485
Overview of PowerShell
FIGURE 17.1 Selecting the Windows PowerShell feature.
used to easily query disk space and installed patches. Examples of using WMI are shown
later in this chapter.
Installing PowerShell
As of Windows Server 2008, adding the PowerShell feature is easy using the new Server
Manager application. With previous versions of Windows, PowerShell was a separate
install, which required downloading and installing an external package.
To install PowerShell on Server 2008, start Server Manager, go to the Features node, then
click Add Features, and simply check the box for Windows PowerShell, as shown in Figure
17.1.
17
PowerShell Console
You can accessing PowerShell directly from the Start menu, by opening All Programs, and
choosing Windows PowerShell 1.0, then finally Windows PowerShell (alternatively, on
some systems, such as Windows 7, you can find the Windows PowerShell folder under the
Accessories folder in the Start menu). The Windows PowerShell console opens, as shown
in Figure 17.2.
Download from www.wowebook.com
ptg
486

FIGURE 17.2 Opening the PowerShell console.
NOTE
The prompt displayed in examples of the PowerShell console in this chapter has been
changed from the default.
Scriptable and Interactive
PowerShell can be used as a scripting language, by creating reusable scripts that can auto-
mate various tasks, and it can also be used interactively, by opening up a console window
and entering commands line by line.
In interactive mode, PowerShell is intelligent enough to know when a command is not
complete and actually displays >> on a new line when it believes a complete command
has not been entered.
Default Security
After PowerShell has been installed, it is very secure out of the box. Here are two of the
default security features:
. PowerShell cannot run any scripts. If you attempt to double-click on any .ps1 script,
it simply opens the contents in Notepad.
. PowerShell cannot be accessed remotely.
CHAPTER 17 Administering SQL Server 2008 with PowerShell
Download from www.wowebook.com
ptg
487
Overview of PowerShell
17
Execution Policy
By default, PowerShell can only be used interactively from the console. This is part of the
default security. To be able to actually run scripts, you must set the execution policy. The
easiest way to set this policy is to use the Set-ExecutionPolicy cmdlet, as follows:
PS>Set-ExecutionPolicy RemoteSigned
Basically, when you use the value RemoteSigned, PowerShell is set to be able to run scripts
that have been created locally, but if a script is downloaded from the Internet, for

example, it must be signed.
NOTE
The details of the different execution policy settings available or the advantages and
disadvantages of different possibilities are not covered in this chapter. Using
RemoteSigned is one of the better trade-offs between functionality and security for
most users.
Profiles
As users become more and more familiar with PowerShell, they typically develop
customizations that they may want to save for the next time PowerShell is opened.
PowerShell has several profiles that can be used to configure user and system-wide
settings. The system-wide profile is easy to access using the following:
PS>notepad $profile
NOTE
On a new install, this file typically doesn’t exist, so don’t be surprised if a window pops
up asking you to create the file. Adding commands to the profile is usually as easy as
adding the exact same commands that you would execute in the shell directly into the
profile.
Built-in Help Features
As mentioned earlier, cmdlets are the most basic component of PowerShell. Three of these
cmdlets are essential in attempting to learn PowerShell. Even advanced users may still use
these cmdlets on a daily basis:
. Get-Command—This cmdlet is essential in discovering what commands can be used
and what might be available on the system to help with a certain task.
. Get-Help—When you are looking for additional details, specifically on other
cmdlets, this is the main cmdlet to use.
Download from www.wowebook.com
ptg
488
. Get-Member—Absolute beginners don’t typically start using this cmdlet when first
initiated into PowerShell, but for advanced users, and easier discovery, this cmdlet is

very useful.
Let’s look at each of these cmdlets in more detail.
Get-Command
The Get-Command cmdlet can be used to get a listing of an entire list of cmdlets on the
system, but it can also be used to get cmdlets that can be used for a specific task or
purpose. For example, Get-Command alone in the console prints the entire list of available
cmdlets available in the current console:
PS>Get-Command
If this is the first time you have ever opened a PowerShell console, how do you write to
the console? How about displaying something as simple as “Welcome to SQL 2008”? You
can pass something basic to Get-Command, such as the string ”*write*”:
PS>Get-Command *write*
What results is a listing of all the cmdlets that have the string ”write” in any part of
their name.
In addition, the preceding command also displays any applications and aliases (aliases are
discussed later in this chapter) found in the current user’s path.
PowerShell can be pretty smart. The preceding sample is actually a shortcut for something
longer like this:
PS>Get-Command -Name *write*
Based on how the cmdlet is programmed, cmdlets can automatically assign a particular
value to a parameter even when the parameter isn’t explicitly typed out.
Originally, we were looking for a cmdlet to display something on the console and found
the cmdlet Write-Host. Let’s try it:
PS>Write-Host “Welcome to SQL 2008”
Get-Help
The learning curve with PowerShell can be relatively steep. Sometimes you can find a
particular command for a particular task, such as the Write-Host cmdlet in the preceding
section, but you might not always be sure how to actually use it. Write-Host is simple, but
what if Write-Host had other useful features, or help was required for some other cmdlet?
Get-Help is a very useful cmdlet. Just using Get-Help alone provides some default help

information:
PS>Get-Help
CHAPTER 17 Administering SQL Server 2008 with PowerShell
Download from www.wowebook.com
ptg
489
Overview of PowerShell
17
To get help on a particular cmdlet, you can use Get-Help and pass the other cmdlet as an
argument:
PS>Get-Help Write-Host
That approach might not provide a lot of useful information; perhaps the –Full and
–Examples parameters are more useful:
PS>Get-Help Write-Host -Full
Passing the –Full parameter gives a detailed description of the cmdlet and all its parame-
ters (including what types of values they accept). If you are a more experienced user, the
–Examples parameter is very useful, because it just gives some examples of using the
cmdlet, which is an easy way to remember the syntax of a particular command:
PS>Get-Help Write-Host -Examples
NOTE
Get-Help works on other cmdlets, but it can also be used when you are looking for
additional details on other concepts in PowerShell. To get a listing of the built-in help
for various concepts in PowerShell, you can run the command Get-Help about_*.
Get-Member
Because everything in PowerShell is object based, some of the features that can be accessed
are always visible. To find out more about a particular object, you can use the Get-Member
cmdlet to look at all its members (the more interesting members of a .NET object are
usually its properties and methods).
Using something simple like ”AdventureWorks2008R2”, you can easily look at PowerShell’s
members (possibly without having to consult any .NET developer-focused documenta-

tion). ”AdventureWorks2008R2” is a string—in other words, a combination of alphanu-
meric characters (that can include spaces). The following example is another way to
display a string in the PowerShell console:
PS>”AdventureWorks2008R2”
PowerShell automatically recognizes this is a simple string and displays it.
A string can be easily displayed to the console, but what else can you do with a string
object? In the .NET Framework, a string is really a System.String object. The .NET
Framework provides a lot of functionality that can be used to deal with strings. Now let’s
consider another example:
PS>” AdventureWorks2008R2”|Get-Member
Download from www.wowebook.com
ptg
490
From the preceding command, more information is displayed now, including
TypeName:System.String, which confirms that this is a System.String object. One partic-
ular feature that Get-Member indicates is that there is a ToLower method supported by this
particular object:
PS>”AdventureWorks2008R2”.ToLower()
In this example, the ToLower method of the System.String object is used to change the
string into all lowercase letters.
PowerShell Scripting Basics
The following sections cover some of the basics of scripting with PowerShell. We hope this
information will help you understand how you can use PowerShell in various situations to
automate various tasks.
A Few Basic Cmdlets
Following is a list of a few basic cmdlets and how they can be used, with a brief example:
. Get-ChildItem (aka dir, gci)—Cmdlet used to list child items in a provider. Mostly
used to list things such as files and directories in a file system. Example: Get-
ChildItem *.ps1
. Select-Object—Cmdlet used to retrieve only specific properties. See Get-Help

Select-Object –Examples for examples.
. Group-Object—Cmdlet used to group objects based on their properties. See Get-Help
Group-Object –Examples for examples.
. Sort-Object—Cmdlet used to sort objects based on their properties. See Get-Help
Sort-Object –Examples for examples.
. Read-Host—Cmdlet used to read input from the screen, usually from a user, before
continuing. Example: Read-Host “Enter a database name”.
. Measure-Command—Cmdlet used to measure how much time a particular scriptblock
took to run. Example: Measure-Command {Get-Command}.
. Write-Host—Cmdlet used to basically display output to the console. This cmdlet
was covered earlier.
. New-Object—Cmdlet used to create an instance of a .NET (or COM) object. Examples
are provided later.
. Get-Alias—Cmdlet used to get a listing of the aliases on the system. Get-Alias,
with no arguments, lists all the aliases configured on the local system.
. Get-Content—Cmdlet used to read the contents of a file. Typically, only text-based
files are supported. Example: Get-Content my_script.ps1.
CHAPTER 17 Administering SQL Server 2008 with PowerShell
Download from www.wowebook.com
ptg
491
PowerShell Scripting Basics
17
. Add-Content—Cmdlet used to add or append content to a file. Example: Add-
Content my_file.txt “testing”.
. Set-Content—Cmdlet used to set the contents of a file (it overwrites any existing
content). Example: Set-Content my_file.txt “testing 123”.
. Start-Transcript—Cmdlet used also with Stop-Transcript to record everything in
the console to a specific text file. Example: Start-Transcript.
Creating a PowerShell Script

Creating a PowerShell script is as simple as placing a few commands into a .ps1 script and
then invoking that script. Here’s a simple example of putting the Write-Host cmdlet into
a script and then running it.
PS> add-content c:\temp\test.ps1 “Write-Host `testing`”
PS>c:\temp\test.ps1
testing
PS>
In the preceding example, a Write-Host cmdlet was placed in a file named test.ps1, and
then the file was invoked. The output resulted in the string ”testing” being output to the
script. Notepad or any other simple text editor could also be used to create more compli-
cated scripts.
Sample PowerShell scripts that directly apply to SQL Server administration are provided
later in this chapter. Refer to the ”The Step-By-Step Examples” section.
Adding Comments
Adding comments to a PowerShell script is as simple as adding the # character at the
beginning of the line. To comment out entire blocks of code, you must use a # on each
line.
NOTE
Another way to comment out blocks of code is to use something called a here string.
This technique is not covered in this book.
Variables
Strings and objects were discussed earlier in this chapter. A very useful feature of
PowerShell, and thus of SQL-PowerShell, is the ability to place objects into a variable. This
allows you to run any kind of command and place any objects produced into a variable
for later use.
Examples of using variables are presented later in this chapter. For now, a string can be
easily saved as a variable:
PS>$var=”AdventureWorks2008R2”
Download from www.wowebook.com
ptg

492
PS>$var
AdventureWorks2008R2
In the preceding example, the string is saved as the variable $var and then output to the
script when the variable is simply invoked:
PS>$database=read-host “Enter a database name”
Enter a database name:AdventureWorks2008R2
PS>$database
AdventureWorks2008R2
The Read-Host cmdlet was introduced briefly already. In this example, the Read-Host
cmdlet is used to read input from the console, and the information input is passed to the
$database variable.
NOTE
When you perform certain actions in a script, a function, and even from the command
line, the scope assigned to the variable or function determines how this variable will be
seen by other scripts, functions, and so on. The details of scoping are not discussed
any further, but it is still an important concept to remember as you use PowerShell
more and more.
NOTE
You can issue the Get-Help about_shell_variable and Get-Help about_scope
commands in Powershell for more information and examples about shell variables.
An example provided later in this chapter demonstrates that objects much more compli-
cated than simple strings can be saved to a variable for later use.
Escaping Characters
Often a special character may be used—for example, in DOS commands—but PowerShell
tries to interpret it differently. Let’s consider the dollar sign character ($). PowerShell
normally tries to interpret it as a variable:
PS C:\> $var=”$5 discount”
PS C:\> $var
discount

PS C:\> $var=”`$5 discount”
PS C:\> $var
$5 discount
PS C:\>
The preceding example shows how the escape character, which is the backtick (`), is used
to escape the dollar sign, so that PowerShell doesn’t try to interpret the character literally
as the beginning of a variable.
CHAPTER 17 Administering SQL Server 2008 with PowerShell
Download from www.wowebook.com
ptg
493
PowerShell Scripting Basics
17
NOTE
You can execute t he Get-Help about_escape_character command in PowerShell for
more information and examples.
Special Variable $_
In PowerShell, $_ is a special variable that represents the current object in the pipeline.
When several cmdlets are piped together, this special variable may be used often. Several
examples of using this special variable are shown later in this chapter.
NOTE
A special variable named $input also represents objects passed along the pipeline,
but we do not look at this variable in any further detail in this chapter.
NOTE
See Get-Help about_automatic_variables for more information and examples.
Joining Variables and Strings
The concept of objects was already introduced briefly. When you are dealing with simple
strings, you can easily concatenate them together using the plus (+) sign to create a new
string:
PS>$last_name=”Doe”

PS>$first_name=”John”
PS>$full_name=$last_name+”, “+$first_name
PS>$full_name
Doe, John
PS>
In this example, two variables containing simple strings are defined, and they are simply
concatenated together to create a third variable, which is then displayed to the console.
NOTE
This kind of concatenation works when both variables are strings. An error may be
returned if the variable is of another data type.
An example is provided later with the AdventureWorks2008R2 database where string vari-
ables from two different columns in the same table will be joined together using this
feature.
Download from www.wowebook.com

×