Before understanding how to use PowerShell to manage
SharePoint, an administrator must first understand how PowerShell
functions and must conceptualize the concepts used with PowerShell.
Getting Started with Windows PowerShell
PowerShell is available on all
new Microsoft operating systems, and administrators can begin learning
PowerShell even when SharePoint 2010 is not installed. To make sure that
the latest version of PowerShell is installed, check the Microsoft
PowerShell scripting center (http://technet.microsoft.com/en-us/scriptcenter/default.aspx). All the examples in this book were written with PowerShell 2.0.
To start working with PowerShell,
go to Start, All Programs, Accessories, Windows PowerShell and run
Windows PowerShell. This starts the PowerShell shell that can be used
for typing PowerShell commands and executing scripts. The default
PowerShell shell is shown in Figure 1.
On a computer with
SharePoint installed, a SharePoint 2010-branded PowerShell shell with
preloaded SharePoint cmdlets is installed. To start this shell, go to
Start, All Programs, Microsoft SharePoint 2010 Products, SharePoint 2010
Management Shell. The shell also supports both standard command-line
commands and the legacy STSADM command-line tool.
Using PowerShell to Display “Hello World!”
A
common task performed when learning a new language is how to display
“Hello World!”. Creating such an application with PowerShell is simple.
Type the following into a shell (you can omit lines starting with #.
Everything after # is a comment) and press Enter:
# To comment in PowerShell use a Hash tag followed by your comments.
Write-Host "Hello World!" # you can also put comments after your command
PowerShell scripts can also be
saved to a file and executed. Save this Hello World sample to
HelloWorld.ps1. Use the standard command-line cd command to navigate to folder in which HelloWorld.ps1 is saved. To execute the script, type the following to the shell:
Using the Integrated Scripting Environment
PowerShell comes with an
integrated scripting environment to ease the creation and testing of
scripts and functions. The scripting environment is available in Start,
All Programs, Windows PowerShell 2.0, Windows PowerShell ISE. PowerShell
ISE is shown in Figure 2.
Before
running any PowerShell cmdlet, make sure you have loaded the
appropriate snap-in. The following code checks if SnapIn has been loaded
and loads it if necessary:
if((Get-PSSnapin | Where {$_.Name -eq "Microsoft.SharePoint.PowerShell"}) -eq $null) {
Add-PSSnapin Microsoft.SharePoint.PowerShell;
However, if you will be
running these samples from the SharePoint 2010 Management Shell, the
SharePoint PowerShell snap-in will be preloaded for you, and you can
bypass this step.