Addison-Wesley Professional
Your source for the news, opinions, and reader reaction on the industry’s hottest controversy.
In this chapter:
What Is Windows PowerShell?
Downloading and Installing PowerShell Community Extensions
Testing the WPS Extensions
Downloading and Installing the PowerShellPlus
Testing the WPS IDE
This chapter introduces Windows PowerShell and helps you set up your environment. In addition, the chapter provides a few easy examples that demonstrate how to use PowerShell.
What Is Windows PowerShell?
Windows PowerShell (WPS) is a new .NET-based environment for console-based system administration and scripting on Windows platforms. It includes the following key features:
A set of commands called commandlets
Access to all system and application objects provided by Component Object Model (COM) libraries, the .NET Framework, and Windows Management Instrumentation (WMI)
Robust interaction between commandlets through pipelining based on typed objects
A common navigation paradigm for different hierarchical or flat information stores (e.g., file system, registry, certificates, Active Directory, environment variables)
An easy-to-learn, but powerful scripting language with weak and strong variable typing
A security model that prevents the execution of unwanted scripts
Tracing and debugging capabilities
The ability to host WPS in any application
This book includes syntax and examples for these features, except the last one, which is an advanced topic that requires in-depth knowledge of a .NET language such as C#, C++/CLI, or Visual Basic .NET.
A Little Bit of History
The DOS-like command-line window survived many Windows versions in almost unchanged form. With WPS, Microsoft now provides a successor that does not just compete with UNIX shells, it surpasses them in robustness and elegance. WPS could be called an adaptation of the concept of UNIX shells on Windows using the .NET Framework, with connections to WMI.
Active Scripting with Windows Script Host (WSH, pronounced “wish”) is much too complex for many administrators because it presupposes much knowledge about object-oriented programming and COM. The many exceptions and inconsistencies in COM make WSH and the associated component libraries hard to learn.
Even during the development of Windows Server 2003, Microsoft admitted that they had asked UNIX administrators how they administer their operating system. The short-term result was a large number of additional command-line tools included in Windows Server 2003. However, the long-term goal was to replace the DOS-like command-line window of Windows with a new, much more powerful shell.
Upon the release of the Microsoft .NET Framework in 2002, many people were expecting a “WSH.NET.” However, Microsoft stopped the development of a new WSH for the .NET Framework because it foresaw that using .NET-based programming languages such as C# and Visual Basic .NET would require administrators to know even more about object-oriented software development.
Microsoft recognized the popularity of and satisfaction with UNIX shells and decided to merge the pipelining concept of UNIX shells with the .NET Framework. The goal was to develop a new shell that was simple to use but nearly as robust as a .NET program. The result: WPS.
In the first beta version, the new shell was presented under the code name Monad at the Professional Developer Conference (PDC) in October 2003 in Los Angeles. After the intermediate names Microsoft Shell (MSH) and Microsoft Command Shell, the shell received its final name, PowerShell, in May 2006. The final version of WPS 1.0 was released on November 11, 2006 at TechEd Europe 2006.
Note – The main architect of WPS 1.0 was Jeffrey Snover. He is always willing to discuss his “baby” and answer questions. At large international Microsoft conferences, such as the Professional Developer Conference (PDC) and TechEd, you can easily find him; he is the only person at the Microsoft booths wearing a tie.
Why Use WPS?
If you need a reason to use WPS, here it comes. Just consider the following solution for one common administrative task in both the old WSH and the new WPS.
An inventory script for software is to be provided that will read the installed MSI packages using WMI. The script will get the information from several computers and summarize the results in a CSV file (softwareinventory.csv). The names (or IP addresses) of the computers to be queried are read from a TXT file (computers.txt).
The solution with WSH (Listing 1.1) requires 90 lines of code (including comments and parameterizing). In WPS, you can do the same thing in just 13 lines (Listing 1.2). If you do not want to include comments and parameterizing, you need just one line (Listing 1.3).
Listing 1.1 Software Inventory Solution 1: WSH
Option Explicit
' --- Settings
Const InputFileName = "computers.txt"
Const OutputFileName = "softwareinventory.csv"
Const Query = "SELECT * FROM Win32_Product where not
Vendor like '%Microsoft%'"
Dim objFSO ' Filesystem Object
Dim objTX ' Textfile object
Dim i ' Counter
Dim Computer ' Current Computer Name
Dim InputFilePath ' Path for InputFile
Dim OutputFilePath ' Path of OutputFile
' --- Create objects
Set objFSO = CreateObject("Scripting.FileSystemObject")
' --- Get paths
InputFilePath = GetCurrentPath & "" & InputFileName
OutputFilePath = GetCurrentPath & "" & OutputFileName
' --- Create headlines
Print "Computer" & ";" & _
"Name" & ";" & _
"Description" & ";" & _
"Identifying Number" & ";" & _
"Install Date" & ";" & _
"Install Directory" & ";" & _
"State" & ";" & _
"SKU Number" & ";" & _
"Vendor" & ";" & _
"Version"
' --- Read computer list
Set objTX = objFSO.OpenTextFile(InputFilePath)
' --- Loop over all computers
Do While Not objTX.AtEndOfStream
Computer = objTX.ReadLine
i = i + 1
WScript.Echo "=== Computer #" & i & ": " & Computer
GetInventory Computer
Loop
' --- Close Input File
objTX.Close
' === Get Software inventory for one computer
Sub GetInventory(Computer)
Dim objProducts
Dim objProduct
Dim objWMIService
' --- Access WMI
Set objWMIService = GetObject("winmgmts:" &_
"{impersonationLevel=impersonate}!" & Computer &_
"rootcimv2")
' --- Execeute WQL query
Set objProducts = objWMIService.ExecQuery(Query)
' --- Loop
For Each objProduct In objProducts
Print _
Computer & ";" & _
objProduct.Name & ";" & _
objProduct.Description & ";" & _
objProduct.IdentifyingNumber & ";" & _
objProduct.InstallDate & ";" & _
objProduct.InstallLocation & ";" & _
objProduct.InstallState & ";" & _
objProduct.SKUNumber & ";" & _
objProduct.Vendor & ";" & _
objProduct.Version
Next
End Sub
' === Print
Sub Print(s)
Dim objTextFile
Set objTextFile = objFSO.OpenTextFile(OutputFilePath, 8, True)
objTextFile.WriteLine s
objTextFile.Close
End Sub
' === Get Path to this script
Function GetCurrentPath
GetCurrentPath = objFSO.GetFile (WScript.ScriptFullName).ParentFolder
End Function
Listing 1.2 Software Inventory Solution 2: WPS
# Settings
$InputFileName = "computers.txt"
$OutputFileName = "softwareinventory.csv"
$Query = "SELECT * FROM Win32_Product where not
Vendor like '%Microsoft%'"
# Read computer list
$Computers = Get-Content $InputFileName
# Loop over all computers and read WMI information
$Software = $Computers | foreach { get-wmiobject -query $Query -
computername $_ }
# Export to CSV
$Software | select Name, Description, IdentifyingNumber, InstallDate,
InstallLocation, InstallState, SKUNumber, Vendor, Version |
export-csv $OutputFileName -notypeinformation
Listing 1.3 Software Inventory Solution 3: WPS Pipeline Command
Get-Content "computers.txt" | Foreach {Get-WmiObject -computername
$_ -query "SELECT * FROM Win32_Product where not
Vendor like '%Microsoft%'" } | Export-Csv "Softwareinventory.csv"
–notypeinformation
Downloading and Installing WPS
Windows Server 2008 is the first operating system that includes WPS on the DVD. However, it is an additional feature that can be installed through Add Feature in the Windows Server 2008 Server Manager.
WPS can be downloaded (see Figure 1.1) and installed as an add-on to the following operating systems:
Windows XP for x86 with Service Pack 2
Windows XP for x64 with Service Pack 2
Windows Server 2003 for x86 with Service Pack 1
Windows Server 2003 for x64 with Service Pack 1
Windows Server 2003 for Itanium with Service Pack 1
Windows Vista for x86
Windows Vista for x64
Note that WPS is not included in Windows Vista, although Vista und WPS were released on the same day. Microsoft decided not to ship any .NET-based applications with Vista. Only the .NET Framework itself is part of Vista.
PowerShell Download Page – https://www.microsoft.com/windowsserver2003/technologies/management/powershell/download.mspx
Figure 1.1
WPS download website
WPS requires that .NET Framework 2.0 or later be installed before running WPS setup. Because Vista ships with .NET Framework 3.0 (which is a true superset of 2.0), no .NET installation is required for it. However, on Windows XP and Windows Server, you must install .NET Framework 2.0, 3.0, or 3.5 first (if they are not already installed by another application).
Microsoft .NET Framework 3.0 Redistributable Package – https://www.microsoft.com/downloads/details.aspx?FamilyId=10CC340B-F857-4A14-83F5-25634C3BF043&displaylang=en
The setup routine installs WPS to the directory %systemroot% system32WindowsPowerShellV1.0 (on 32-bit systems) or %systemroot% Syswow64WindowsPowerShellV1.0 (for 64-bit systems). You cannot change this folder during setup.
TIP – If for any reason you want to uninstall WPS, note that WPS is considered a software update to the Windows operating system (i.e., not a normal application). Therefore, in the Add or Remove Programs control panel applet, it is not listed as a program; instead, it is listed as an update called Hotfix for Windows (KB x). The Knowledge Base (KB) number varies on different operating systems. However, you can identify WPS installation in the list by its icon (see Figure 1.2). On Windows XP and Windows Server 2003, you must check the Show Updates check box to see the WPS installation.
Taking WPS for a Test Run
This section includes some commands to enable you to try out a few WPS features. WPS has two modes, interactive mode and script mode, which are covered separately.
Figure 1.2
The uninstall option for WPS is difficult to find. (This screenshot is from Windows Server 2003.)
WPS in Interactive Mode
First, you’ll use WPS in interactive mode.
Start WPS. An empty WPS console window will display (see Figure 1.3). At first glance, you might not see much difference between it and the traditional Windows console. However, there is much more power in WPS, as you will soon see.
At the command prompt, type get-process and then press the Return key. A list of all running processes on your local computer will display (see Figure 1.4). This was your first use of a simple WPS commandlet.
Note – Note that the letter case does not matter. WPS does not distinguish between uppercase and lowercase letters in commandlet names.
Figure 1.3
Empty WPS console window
Figure 1.4Get-Process commandlet output
The
At the command prompt, type get-service i*. A list of all installed services with a name that begins with the letter I on your computer will display (see Figure 1.5). This was your first use of a commandlet with parameters.
Figure 1.5
A filtered list of Windows services
Type get- and then press the Tab key several times. You will see WPS cycling through all commandlets that start with the verb get. Microsoft calls this feature tab completion. Stop at Get-Eventlog. When you press Enter, WPS prompts for a parameter called logname (see 1.6). Logname is a required parameter. After typing Application and pressing Return, you will see a long list of the current entries in your Application event log.
WPS prompts for a required parameter
The last example in this section introduces you to the pipeline features of WPS. Again, we want to list entries from a Windows event log, but this time we want to get only some entries. The task is to get the most recent ten events that apply to printing. Enter the following command, which consists of three commandlets connected via pipes (see Figure 1.7):
Get-EventLog system | Where-Object { $_.source -eq "print" }
| Select-Object -first 10
Note that WPS seems to get stuck for a few seconds after printing the first ten entries. This is the correct behavior because the first commandlet (Get-EventLog) will receive all entries. The filtering is done by the subsequent commandlets (Where-Object and Select-Object). Unfortunately, Get-EventLog has no included filter mechanism.
Figure 1.7
Filtering event log entries
WPS in Script Mode
Now it’s time to try out PowerShell in script mode and incorporate a WPS script. A WPS script is a text file that includes commandlets/elements of PowerShell Script Language (PSL). The script in this example creates a new user account on your local computer.
Open Windows Notepad (or any other text editor) and enter the following lines of script code (which consist of comments, variable declarations, COM library calls, and shell output):
Listing 1.4 Create a User Account
### PowerShell Script
### Create local User Acount
# Variables
$Name = "Dr. Holger Schwichtenberg"
$Accountname = "HolgerSchwichtenberg"
$Description = "Author of this book / Website: powershell24.com"
$Password = "secret+123"
$Computer = "localhost"
"Creating User on Computer $Computer"
# Access to Container using the COM library
"Active Directory Service Interface (ADSI)"
$Container = [ADSI] "WinNT://$Computer"
# Create User
$objUser = $Container.Create("user", $Accountname)
$objUser.Put("Fullname", $Name)
$objUser.Put("Description", $Description)
# Set Password
$objUser.SetPassword($Password)
# Save Changes
$objUser.SetInfo()
"User created: $Name"
Save the text file with the name createuser.ps1 into the directory c:temp. Note that the file extension must be .ps1.
Now start WPS. Try to start the script by typing c:temp createuser.ps1. (You can use tab completion for the directory and filenames.) This attempt will fail because script execution is, by default, not allowed in WPS (see Figure 1.8). This is not a bug; it is a security feature. (Remember the Love Letter worm for WSH?)
Figure 1.8
Script execution is prohibited by default.
For our first test, we will weaken the security a little bit (just a little). We will allow scripts that reside on your local system to run. However, scripts that come from network resources (including the Internet) will need a digital signature from a trusted script author. Later in this book you learn how to digitally sign WPS scripts. You also learn to restrict your system to scripts that you or your colleagues have signed.
To allow the script to run, enter the following:
Set-ExecutionPolicy remotesigned
Then, start the script again (see Figure 1.9). Now you should see a message that the user account has been created (see Figure 1.10).
Figure 1.9
Running your first script to create a user account
Figure 1.10
The newly created user account
Downloading and Installing PowerShell Community Extensions
WPS 1.0 includes only 129 commandlets. You might ask why I wrote only. You will notice soon that the most important commandlets are those with the verbs get and set. And the number of those commandlets is quite small compared to the large number of objects that Windows operating systems provide. All the other commandlets are, more or less, related to WPS infrastructure (e.g., filtering, formatting, and exporting).
PowerShell Community Extensions (PSCX) is an open source project (see Figure 1.11) that provides additional functionality with commandlets such as Get-DhcpServer, Get-DomainController, Get-MountPoint, Get-TerminalSession, Ping-Host, Write-GZip, and many more. Microsoft leads this project, but any .NET software developer is invited to contribute. New versions are published on a regular basis. At the time of this writing, version 1.1.1 is the current stable release.
Download PowerShell Community Extensions – https://www.codeplex.com/PowerShellCX
PSCX is provided as a setup routine that should be installed after WPS has been installed successfully.
PowerShell Community Extension website
You can incorporate additional functionality of PSCX into WPS by using a profile script (see Figure 1.12). Just copy this profile script to your My Documents/Windows PowerShell directory, if you want, during PSCX setup. As a beginner, you should use this option.
Figure 1.12
The PSCX profile script that was created during PSCX setup
Testing the WPS Extensions
The installation of PSCX changes the WPS console just a bit. Instead of the current path, the prompt now contains a counter. However, the path does display in the window’s title.
Start WPS and type Get-DomainController (if your computer is a member of an Active Directory) or test PSCX by using Ping-Host with any computer on your network (see Figure 1.13).
Figure 1.13Get-DomainController and Ping-Host
Testing
Downloading and Installing the PowerShellPlus
Unfortunately, Microsoft does not provide a script editor for WPS yet. However, a few third-party editors support WPS (see Chapter 9, “PowerShell Tools”). Throughout this book, we use PowerShellPlus Editor, which is free for noncommercial use.
A previous editor called PowerShell IDE from the same author was free even for commercial use. However, PowerShell IDE never made it to a final release and was discontinued.
The PowerShellPlus Editor is part of PowerShellPlus. PowerShellPlus consists of the editor and a console that provides IntelliSense while using the PowerShell interactively.
PowerShellPlus Website – https://www.powershell.com
PowerShellPlus does not need any setup. It is a true .NET application with XCopy deployment. You just unpack the ZIP file to the directory of your choice and start the PowerShellPlus.exe that is part of the package.
Testing the WPS IDE
The PowerShellPlus has, according to the WPS console, two modes: an interactive mode and a script mode. After starting the PowerShellPlus, you will see the interactive mode. You can use any commandlet (or pipeline). When you press Return, the commandlet is executed, and the result displays in the same window. The handy feature is the IntelliSense. If you enter Get-P, you will see a drop-down list of the available commandlets start with these letters.
Figure 1.14
WPS IDE in interactive mode
To use the PowerShellPlus in script mode, click Code Editor and create a new script file (New/PowerShell Script) or open an existing script PS1 file (Open). Now open the script file CreateUser.ps1 that you created earlier. You will see line numbers, and you will encounter the same IntelliSense features that you have in interactive mode. To run the script, click the Run symbol in the toolbar (see Figure 1.15). The result will display in the interactive Windows in the background.
WARNING – Make sure the user account does not exist before running the script. Otherwise the script will fail with error “The account already exists.”
WPS IDE in script mode
Another nice feature is debugging. Place the cursor on any line in your script and click the Debugging icon. Next, go to any line and press F9. This creates a red circle next to that line, called a breakpoint. Now run the script. You will see the PowerShellPlus Editor executing the script in slow motion, marking the current line yellow and stopping at the line with the breakpoint (see Figure 1.16). In the Variables Inspector window, you can inspect the current value of all variables. In the interactive window, you can type any WPS command that will be executed within the current context. That is, you can interactively access all script variables. To continue the script, hit F8 or click the Continue icon in the toolbar.
Figure 1.16
Script debugging with the WPS IDE
Code snippets are also a nice feature of the PowerShellPlus. In a script file, click Snippet/Insert on the toolbar or select Insert Snippet in the context menu in the main Editor window. You will be able to select a snippet. You can create you own snippets with the PowerShellPlus (via Snippets/ New on the toolbar).
Summary
Windows PowerShell is a new .NET-based environment for scripting and is an interactive command-line shell. WPS is an optional feature on Windows Serv er 2008 and an add-on for Windows XP, Vista, and Server 2008. Commands in WPS are called commandlets. The PSCX extends WPS with additional commandlets.
The PowerShellPlus is an alternative shell for WPS commands and editor for WPS scripts.
In the next chapter, you learn much more about commandlets and pipelines. You also learn how to get help if you are seeking a command or the available options for a commandlet.
Copyright © 2007 Pearson Education. All rights reserved.





