1. INTRODUCING POWERSHELL
System administrators are realizing the
productivity gains that can be achieved from PowerShell, the unified
scripting environment provided by Microsoft. Reusing scripts of
commonly executed tasks is much faster and less error prone than
repeatedly clicking through dialogs.
PowerShell was first unveiled to the world at the
Microsoft Professional Developers Conference with a code name of Monad
in 2003. Following a beta release, version 1 was officially released in
2006, and since then PowerShell has become a deeply integrated
component of Windows. Indeed, SQL Server 2012 takes PowerShell so
seriously that PowerShell 2.0 is a prerequisite, and SQL Server will
not install if PowerShell is not already installed on the system. The
initial SQL Server and PowerShell integration that started out with the
SQL Server Database Engine now provides support for SSIS and SSAS in
SQL Server 2012. PowerShell is also still in active development, which
proceeds rapidly; the PowerShell 3.0 release is expected in late 2012.
2. GETTING STARTED WITH POWERSHELL
PowerShell is an object-oriented,
command-line and scripting engine created by Microsoft and built on top
of the .NET Framework. PowerShell provides full access to COM, WMI, the
Windows Registry, and the .NET Framework.
The PowerShell product team created a design that
enables developers to extend and enhance the environment with new
cmdlets, providers, and modules. This deep Windows integration
out-of-the-box and the extensibility of the framework means that you
can create scripts to perform nearly any conceivable task.
You can think of PowerShell as an alternative
view of your environment, as opposed to the familiar GUI experience.
Every time you run a cmdlet, PowerShell responds with a result that you
can evaluate and investigate further; and because everything returned
is an object, you can drill down for further details. You can run
cmdlets repeatedly and scroll through their history in the command
window to see how you got to where you are. If you find you are
repeatedly running the same pattern of cmdlets, you can package them up
into a script or function and reuse complex composite scripts of
cmdlets with a single new script or function name.
As mentioned earlier, PowerShell operates on
objects. This is a very important aspect of its design that makes life
simpler for you because you can take the results of one cmdlet and pass
them straight into the next cmdlet as input. This is known as the pipeline and it differentiates PowerShell from other command shells, which have traditionally relied on text streams.
The productivity benefits that result from using
PowerShell — automating repetitive tasks and reducing errors — are
obvious, but PowerShell is also great for investigation and
troubleshooting; and its command-line interface is useful when you are
trying to investigate an issue. Imagine a situation in which you need
to investigate a poorly performing server that you have not worked on
before. With the following simple command you can quickly identify
where the server resources are being consumed. This example shows how
you can determine the top ten processes consuming the most CPU
resources:
Get-Process | Sort-Object cpu -Descending | Select-Object -First 10
This simple statement has taken all the
processes running on the computer, sorted them by CPU utilization
descending, and then selected the top 10 processes. You don’t have to
wait for a user interface to load, which eliminates putting additional
strain on the server.
Another troubleshooting question you may wish to
find out is when the computer last booted up. You can also achieve this
with a simple script (code file: PS_LastBootTime01.PS1):
$wmiBootTime = (get-wmiobject Win32_OperatingSystem).lastbootuptime;
[DateTime]$lastBootUpTime =
[Management.ManagementDateTimeConverter]::ToDateTime($wmiBootTime);
$uptime = (Get-Date) - $lastBootUpTime;
Write-Host $lastBootUpTime;
Write-Host $uptime;
In the preceding example I created a
variable and stored the last boot-up time, which is initially a string
when retrieved from WMI. I then converted it into a DateTime object. I calculated the uptime by using the Get-Date
cmdlet, subtracting the date on which the machine was rebooted. I then
displayed the last boot-up time and the uptime in the console.
You can build a suite of such statements and
scripts that you want to run later, and you can easily package them
into a script that you can run on a server. Don’t worry if these
scripts look a little daunting right now.
2.1 The PowerShell Environment
PowerShell 2 is pre-installed on
Windows 7 and Windows Server 2008 R2 operating systems. Although
PowerShell can be installed onto earlier versions of Windows, it is not
immediately obvious from where you can obtain the download. This is
because the actual product name that is indexed by all the popular
Internet search engines is “Windows Management Framework,” not
PowerShell.
Once installed, you can either use PowerShell in
interactive command-line mode (the shell), or use a script editor to
create script files containing multiple statements to execute. To
launch the interactive command line, run PowerShell.exe or find the
“Windows PowerShell” shortcut that is installed in your Start menu.
There is an alternate icon in the Start menu called “Windows PowerShell
Modules”; this is similar to the standard “Windows PowerShell” item,
but while loading the shell it also imports all the modules in the
PowerShell Modules folder. The following PowerShell variable allows you
to discover where the PowerShell modules are located on your machine:
$env:PSModulePath
The environments variable contains many
configuration settings on your system. You can discover all of them by
listing the contents of the variable as shown below:
PS > get-childitem env:
When you install PowerShell packs as
part of Windows features, the PowerShell modules will be installed
here, which provides a quick way to ensure that every Windows feature
with PowerShell support installed has all its functionality available
to you when you load the command line.
All the commands that you will be familiar with from cmd.exe are available, such as DIR. You will also have access to a wealth of new commands that are provided with PowerShell; these commands are commonly known as cmdlets.
PowerShell ships with a host application, the
PowerShell Integrated Scripting Environment (ISE). This is installed by
default in Windows 7 and can be enabled by installing the “Windows
PowerShell Integrated Scripting Environment (ISE)” feature on Windows
Server 2008 R2. The PowerShell ISE enables you to create script files,
which by convention have an extension of .PS1.
You can also debug and run scripts from within this environment;
although this is a significant improvement from using Notepad and the
command window in PowerShell 1, there is still room for improvement.
I prefer to use PowerGUI, a free PowerShell Scripting Environment that is available for download from www.powergui.org.
PowerGUI also offers a wealth of additional cmdlets that have been
written by the PowerGUI community, providing functionality that is not
available out-of-the-box with PowerShell. If you also use Visual
Studio, you’re in luck, because Adam Driscoll has created a Visual
Studio, extension (VSX) for PowerShell that uses PowerGUI. You can
download the VSX from http://visualstudiogallery.msdn.microsoft.com/01516103-d487-4a7e-bb40-c15ec709afa3; this extension enables you to create, debug, and manage scripts within the Visual Studio IDE.
A growing community of users has contributed
additional cmdlets and modules. The best known and supported set of
community functionality is available at http://pscx.codeplex.com.
The PowerShell Community Extensions (PSCX) utility is worth downloading
and keeping locally because it contains numerous cmdlets, functions,
and modules to facilitate your work with respect to many aspects of
Windows. A set specific to SQL Server, known as the SQL PowerShell
Extensions, is available from http://sqlpsx.codeplex.com.
Security was an important consideration when the
product team created PowerShell. With such an integrated and extensible
scripting and command-line interface, it was critical to consider how
users would be protected from unauthorized scripts executing. A key
feature of this is the Execution Policy, which is a systemwide
configuration that specifies the type of scripts that can be executed
on the computer. Table 1 summarizes the four possible values for the Execution Policy.
TABLE 1: PowerShell Execution Policies
Execution Policy |
Description |
Restricted |
No scripts can be run. Windows PowerShell can be used only in interactive mode. |
AllSigned |
Only scripts signed by a trusted publisher can be run. |
RemoteSigned |
Downloaded scripts must be signed by a trusted publisher before they can be run. |
Unrestricted |
No restrictions; all scripts can be run. |
You can check the current status of the Execution Policy on your computer with the Get-ExecutionPolicy
cmdlet. The following example shows how my computer is currently
configured. As you can see in the example below, the machine is set up
so that downloaded scripts must be signed to run, but scripts created
on the computer don’t have to be signed to run.
PS > Get-ExecutionPolicy
RemoteSigned