First Steps with Windows PowerShell
In this chapter: |
|
What Is Windows PowerShell? |
3 |
Downloading and Installing PowerShell Community Extensions |
16 |
Testing the PowerShell Extensions |
18 |
Downloading and Installing the PowerShellPlus |
19 |
Testing the PowerShell Editor |
20 |
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 (for example, file system, registry, certificates, Active Directory, and 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 it 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.
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 &_ "\root\cimv2") ' --- 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 Script
# 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
Figure 1.1 WPS download website
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.
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).
The setup routine installs WPS to the directory %systemroot%\system32\WindowsPowerShell\V1.0 (on 32-bit systems) or %systemroot%\Syswow64\WindowsPowerShell\V1.0 (for 64-bit systems). You cannot change this folder during setup.
Figure 1.2 The uninstall option for WPS is difficult to find. (This screenshot is from Windows Server 2003.)
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.
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.
Figure 1.3 Empty WPS console window
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.
Figure 1.4 The Get-Process commandlet output
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 Figure 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.
Figure 1.6 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
Figure 1.7 Filtering event log entries
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.
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 consists 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: www.windows-scripting.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