Home > Articles > Operating Systems, Server > Microsoft Servers

First Steps with Windows PowerShell

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.
This chapter is from the book

This chapter is from the book

In this chapter:

What Is Windows PowerShell?


Downloading and Installing PowerShell Community Extensions


Testing the PowerShell Extensions


Downloading and Installing the PowerShellPlus


Testing the PowerShell Editor


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
ccc.gifVendor 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" & ";" & _

' --- 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

' --- Close Input File

' === Get Software inventory for one computer
Sub GetInventory(Computer)

Dim objProducts
Dim objProduct
Dim objWMIService

' --- Access WMI
Set objWMIService = GetObject("winmgmts:" &_
    "{impersonationLevel=impersonate}!\\" & Computer &_
' --- 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 & ";" & _
End Sub

' === Print
Sub Print(s)
Dim objTextFile
Set objTextFile = objFSO.OpenTextFile(OutputFilePath, 8, True)
objTextFile.WriteLine s
End Sub

' === Get Path to this script
Function 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
ccc.gifVendor 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,
ccc.gifInstallLocation, InstallState, SKUNumber, Vendor, Version |
ccc.gifexport-csv $OutputFileName -notypeinformation

Listing 1.3. Software Inventory Solution 3: WPS Pipeline Command

Get-Content "computers.txt" | Foreach {Get-WmiObject -computername
ccc.gif$_  -query "SELECT * FROM Win32_Product where not
ccc.gifVendor like '%Microsoft%'" } |  Export-Csv "Softwareinventory.csv"

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

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

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

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

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

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

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" }
ccc.gif | Select-Object -first 10
Figure 1.7

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
ccc.gif"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
# Save Changes

"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

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

Figure 1.9 Running your first script to create a user account

Figure 1.10

Figure 1.10 The newly created user account

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information

To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.


Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.


If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information

Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.


This site is not directed to children under the age of 13.


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information

If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information

Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents

California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure

Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact

Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice

We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020