Book Excerpt

What is Windows PowerShell?

Essential PowerShell This chapter excerpt from Essential PowerShell, by Holger Schwichtenberg, is printed with permission from Addison-Wesley Professional, Copyright 2008.

Click here to purchase the entire book.

About the author


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 longterm 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 objectoriented 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 technical 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 &_
"\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


ESSENTIAL POWERSHELL

 Part 1: What is PowerShell?
 Part 2: Downloading and Installing PowerShell
 Part 3: PowerShell Community Extensions and PowerShell Plus

Dr. Holger Schwichtenberg is one of Germany's well-known experts for .NET and Windows Scripting technologies, is a Microsoft MVP, a .NET Code Wise Member, a board member of codezone.de, MSDN Online Expert, and a INETA speaker. He has published more than 20 books for Addison Wesley and Microsoft Press in Germany, in addition to more than 400 journal articles, notably for the IT journals iX, DOTNET Pro, and Windows IT Pro. He can be reached at hs@powershell24.com.


This was first published in August 2008

There are Comments. Add yours.

 
TIP: Want to include a code block in your comment? Use <pre> or <code> tags around the desired text. Ex: <code>insert code</code>

REGISTER or login:

Forgot Password?
By submitting you agree to receive email from TechTarget and its partners. If you reside outside of the United States, you consent to having your personal data transferred to and processed in the United States. Privacy
Sort by: OldestNewest

Forgot Password?

No problem! Submit your e-mail address below. We'll send you an email containing your password.

Your password has been sent to: