A Guided Tour of Windows PowerShell

Introduction

Windows PowerShell promises to revolutionize the world of system management and command-line shells. From its object-based pipelines, to its administrator focus, to its enormous reach into other Microsoft management technologies, PowerShell drastically improves the productivity of administrators and power-users alike.

3 comments

  1. Kjartan Þór Kjartansson Posted 16 days and 6 hours ago

    I am reading this now

  2. Kjartan Þór Kjartansson Posted 16 days and 6 hours ago

    Done

  3. Andy Helsby Posted 5 days and 17 hours ago

    Almost feels like this page should come after the preface as the preface explains the syntax, download, code samples etc.

Add a comment

When learning a new technology, it is natural to feel bewildered at first by all the unfamiliar features and functionality. This perhaps rings especially true for users new to Windows PowerShell, because it may be their first experience with a fully featured command-line shell. Or worse, they've heard stories of PowerShell's fantastic integrated scripting capabilities and fear being forced into a world of programming that they've actively avoided until now.

2 comments

  1. CraigLi Posted 9 days and 17 hours ago

    Should be "Windows PowerShell" throughout and not just "PowerShell"

  2. Alan D. Lum Posted 6 days and 19 hours ago

    I don't agree with Mr. Li. I prefer brevity after an initial introduction to the full name. I'd go nuts if say, I read a book that always refers to "Microsoft Windows Vista" instead of just "Vista".

Add a comment

Fortunately, these fears are entirely misguided: PowerShell is a shell that both grows with you and grows on you. Let's take a tour to see what it is capable of:

  • PowerShell works with standard Windows commands and applications. You don't have to throw away what you already know and use.

  • PowerShell introduces a powerful new type of command. PowerShell commands (called cmdlets) share a common Verb-Noun syntax and offer many usability improvements over standard commands.

  • PowerShell understands objects. Working directly with richly structured objects makes working with (and combining) PowerShell commands immensely easier than working in the plain-text world of traditional shells.

  • PowerShell caters to administrators. Even with all its advances, PowerShell focuses strongly on its use as an interactive shell: the experience of entering commands in a running PowerShell application.

  • PowerShell supports discovery. Using three simple commands, you can learn and discover almost anything PowerShell has to offer.

  • PowerShell enables ubiquitous scripting. With a fully fledged scripting language that works directly from the command line, PowerShell lets you automate tasks with ease.

  • PowerShell bridges many technologies. By letting you work with .NET, COM, WMI, XML, and Active Directory, PowerShell makes working with these previously isolated technologies easier than ever before.

  • PowerShell simplifies management of data stores. Through its provider model, PowerShell lets you manage data stores using the same techniques you already use to manage files and folders.

We'll explore each of these pillars in this introductory tour of PowerShell. If you are running Windows 7 or Windows 2008 R2, version two of PowerShell is already installed. If not, visit the download link at http://www.microsoft.com/PowerShell to install it. PowerShell and its supporting technologies are together referred to as the Windows Management Framework.

1 comment

  1. Andy Helsby Posted 5 days and 19 hours ago

    Glad to see a short link to the software rather than Microsoft's long URL's that often break. You may also mention that PowerShell is referenced in this page as the Windows Management Framework Core. For someone who just skips through the page looking for PowerShell it's not that obvious to download the Windows Management Framework Core - after all, this does sound like a different product.

Add a comment

An Interactive Shell

At its core, PowerShell is first and foremost an interactive shell. While it supports scripting and other powerful features, its focus as a shell underpins everything.

Getting started in PowerShell is a simple matter of launching PowerShell.exe rather than cmd.exe—the shells begin to diverge as you explore the intermediate and advanced functionality, but you can be productive in PowerShell immediately.

To launch Windows PowerShell

Click Start→All Programs→Accessories→Windows PowerShell or alternatively,

4 comments

  1. Conan Wills Posted 18 days and 2 hours ago

    This is not the location on my Win7 desktop. It is under Start→All Programs→Accessories→Windows PowerShell. Perhaps just use the second method.

  2. David "Makovec" Moravec Posted 17 days and 22 hours ago

    For PS v2 it's not true anymore. It's under: Start/All Programs/Accessories/Windows PowerShell/Windows PowerShell.

  3. Jonathan Noble Posted 17 days and 7 hours ago

    With different versions of Windows and different architectures, I don't think it's worth trying to say exactly where to look in the Start Menu structure. I'd go with Start->Run as you have below and 'Start and then type "PowerShell" in the search box on Windows 7/Server 2008 R2'.

  4. Philip LaVoie Posted 9 days and 7 hours ago

    either method assumes the installation has already taken place or they are running win7. if it's for all installs for psv2 ya may want to point them to the installer site prior to the launch methods.

Add a comment

Click Start→Run, and then type "PowerShell".

A PowerShell prompt window opens that's nearly identical to the traditional command prompt window of Windows XP, Windows Server 2003, and their many ancestors. The PS C:\Documents and Settings\Lee> prompt indicates that PowerShell is ready for input, as shown in Figure 1, “Windows PowerShell, ready for input”.

Figure 1. Windows PowerShell, ready for input

Windows PowerShell, ready for input

3 comments

  1. Johannes Rössel Posted 19 days and 22 hours ago

    In Example 1, 3rd line, there should be a line break after cd.

  2. David "Makovec" Moravec Posted 17 days and 22 hours ago

    This screenshot is from PS v1.

  3. Clayton McKenzie Posted 17 days and 8 hours ago

    You should move the image for Figure 1 to before the Paragraph beginning "Once you've launched your PowerShell prompt..."

Add a comment

Once you've launched your PowerShell prompt, you can enter DOS-style and Unix-style commands to navigate around the filesystem just as you would with any Windows or Unix command prompt—as in the interactive session shown in Example 1, “Entering many standard DOS and UNIX-style file manipulation commands produces the same results you get when you use them with any other Windows shell”. In this example, we use the pushd, cd, dir, pwd, and popd commands to store the current location, navigate around the filesystem, list items in the current directory, and then return to your original location. Try it!

Example 1. Entering many standard DOS and UNIX-style file manipulation commands produces the same results you get when you use them with any other Windows shell

PS C:\Documents and Settings\Lee> function Prompt { "PS > " }
PS > pushd .
PS > cd PS > dir


    Directory: C:

Mode                LastWriteTime     Length Name
----                -------------     ------ ----
d----         11/2/2006   4:36 AM            $WINDOWS.~BT
d----          5/8/2007   8:37 PM            Blurpark
d----        11/29/2006   2:47 PM            Boot
d----        11/28/2006   2:10 PM            DECCHECK
d----         10/7/2006   4:30 PM            Documents and Settings
d----         5/21/2007   6:02 PM            F&SC-demo
d----          4/2/2007   7:21 PM            Inetpub
d----         5/20/2007   4:59 PM            Program Files
d----         5/21/2007   7:26 PM            temp
d----         5/21/2007   8:55 PM            Windows
-a---          1/7/2006  10:37 PM          0 autoexec.bat
-ar-s        11/29/2006   1:39 PM       8192 BOOTSECT.BAK
-a---          1/7/2006  10:37 PM          0 config.sys
-a---          5/1/2007   8:43 PM      33057 RUU.log
-a---          4/2/2007   7:46 PM       2487 secedit.INTEG.RAW


PS > popd
PS > pwd

Path
----
C:\Documents and Settings\Lee

6 comments

  1. Johannes Rössel Posted 18 days ago

    As for the prompt, I think "PS> " would be nicer than "PS >" because then the command and the prompt are separated by a space (just as the default prompt does. This makes it (imho) easier to read the actual command.

  2. David "Makovec" Moravec Posted 17 days and 22 hours ago

    On third line there should be: PS >cd ... and then fourth line: PS >dir

  3. Aleksandar Nikolic Posted 17 days and 10 hours ago

    I agree with Johannes and would prefer "PS> " (or even "PS>") prompt.

  4. Jonathan Noble Posted 17 days and 6 hours ago

    +1 to having a space on the end of the prompt and (more importantly) a line-break after the cd (again).

  5. Claus Thude Nielsen Posted 9 days and 22 hours ago

    I think this should be broken up in smaller pieces, I and maybe have separate descriptions for each part.. I have read it several times now, and to me in it current form, it feels misplaced.

  6. Andy Helsby Posted 5 days and 19 hours ago

    Is it really wise to launch into a function but not describe why this is necessary. You start off by saying that most commands from dos can be used and the first thing that you type in is not what you would type in a dos prompt.

    Also the cd command is picky about spaces - in dos you could type in cdtemp whereas powershell needs cd temp

Add a comment


In this example, our first command customizes the prompt. In cmd.exe, customizing the prompt like: prompt $P$G. In bash, it looks like: PS1="[\h] \w> ". In PowerShell, you define a function that returns whatever you want displayed. the section called “Write a Function” introduces functions and how to write them.

The pushd command is an alternative name (alias) to the much more descriptively named PowerShell command, Push-Location. Likewise, the cd, dir, popd, and pwd commands all have more memorable counterparts.

Although navigating around the filesystem is helpful, so is running the tools you know and love, such as ipconfig and notepad. Type the command name and you'll see results like those shown in Example 2, “Windows tools and applications such as ipconfig run in PowerShell just as they do in the cmd.exe”.

Example 2. Windows tools and applications such as ipconfig run in PowerShell just as they do in the cmd.exe

PS > ipconfig

Windows IP Configuration


Ethernet adapter Wireless Network Connection 4:

        Connection-specific DNS Suffix .  : hsd1.wa.comcast.net.
        IP Address. . . . . . . . . . . . : 192.168.1.100
        Subnet Mask . . . . . . . . . . . : 255.255.255.0
        Default Gateway . . . . . . . . . : 192.168.1.1
PS > notepad
(notepad launches)

Entering ipconfig displays the IP addresses of your current network connections. Entering notepad runs—as you'd expect—the Notepad editor that ships with Windows. Try them both on your own machine.

Structured Commands (Cmdlets)

In addition to supporting traditional Windows executables, PowerShell introduces a powerful new type of command called a cmdlet (pronounced command-let). All cmdlets are named in a Verb-Noun pattern, such as Get-Process, Get-Content, and Stop-Process.

1 comment

  1. David "Makovec" Moravec Posted 17 days and 21 hours ago

    See it third time here so expect it's an English grammar specific.

Add a comment

PS > Get-Process -Name lsass

Handles  NPM(K)    PM(K)    WS(K) VM(M)   CPU(s)    Id ProcessName
-------  ------    -----    ----- -----   ------    -- -----------
    668      13     6228     1660    46            932 lsass

In this example, you provide a value to the ProcessName parameter to get a specific process by name.

Note

Once you know the handful of common verbs in PowerShell, learning how to work with new nouns becomes much easier. While you may never have worked with a certain object before (such as a Service), the standard Get, Set, Start, and Stop actions still apply. For a list of these common verbs, see Table J.1, “Standard Windows PowerShell common verbs”.

2 comments

  1. David "Makovec" Moravec Posted 17 days and 21 hours ago

    ... or run Get-Verb in your PowerShell console.

  2. Andy Helsby Posted 5 days and 19 hours ago

    The table is probably better as this gives a description of each verb rather than just a listing of the verbs themselves. Maybe it should read For a listing of these common verbs type "Get-Verb" in your PowerShell console or refer to Table J.1 for a list and description.

Add a comment

You don't always have to type these full cmdlet names, however. PowerShell lets you use the Tab key to auto-complete cmdlet names and parameter names:

PS > Get-Pr<TAB> -N<TAB> lsass

For quick interactive use, even that may be too much typing. To help improve your efficiency, PowerShell defines aliases for all common commands and lets you define your own. In addition to alias names, PowerShell only requires that you type enough of the parameter name to disambiguate it from the rest of the parameters in that cmdlet. PowerShell is also case-insensitive. Using the built-in gps alias (that represents the Get-Process cmdlet) along with parameter shortening, you can instead type:

PS > gps -n lsass

Going even further, PowerShell supports positional parameters on cmdlets. Positional parameters let you provide parameter values in a certain position on the command line, rather than having to specify them by name. The Get-Process cmdlet takes a process name as its first positional parameter. This parameter even supports wildcards:

PS > gps l*s

Deep Integration of Objects

PowerShell begins to flex more of its muscle as you explore the way it handles structured data and richly functional objects. For example, the following command generates a simple text string. Since nothing captures that output, PowerShell displays it to you:

PS > "Hello World"
Hello World

The string you just generated is, in fact, a fully functional object from the .NET Framework. For example, you can access its Length property, which tells you how many characters are in the string. To access a property, you place a dot between the object and its property name:

PS > "Hello World".Length
11

All PowerShell commands that produce output generate that output as objects, as well. For example, the Get-Process cmdlet generates a System.Diagnostics.Process object, which you can store in a variable. In PowerShell, variable names start with a $ character. If you have an instance of Notepad running, the following command stores a reference to it:

1 comment

  1. Andy Helsby Posted 5 days and 19 hours ago

    Examples only work with one instance of notepad running, so perhaps... "If you have one instance of Notepad running...."

Add a comment

$process = Get-Process notepad

Since this is a fully functional Process object from the .NET Framework, you can call methods on that object to perform actions on it. This command calls the Kill() method, which stops a process. To access a method, you place a dot between the object and its method name:

$process.Kill()

PowerShell supports this functionality more directly through the Stop-Process cmdlet, but this example demonstrates an important point about your ability to interact with these rich objects.

Administrators As First-Class Users

While PowerShell's support for objects from the .NET Framework quickens the pulse of most users, PowerShell continues to focus strongly on administrative tasks. For example, PowerShell supports MB (for megabyte) and GB (for gigabyte) as some of its standard administrative constants. For example, how many disks will it take to back up a 40GB hard drive to CD-ROM?

PS > 40GB / 650MB
63.0153846153846

While the .NET Framework is traditionally a development platform, it contains a wealth of functionality useful for administrators, too! In fact, it makes PowerShell a great calendar. For example, is 2008 a leap year? PowerShell can tell you:

1 comment

  1. Scott Blomquist Posted 7 days and 16 hours ago

    "doesn't mean you can't still use [it] for admin tasks" doesn't read clearly. I think you mean "just because PS is admin-focused doesn't mean it can only be used for admin tasks".

Add a comment

PS > [DateTime]::IsLeapYear(2008)
True

Going further, how might you determine how much time remains until summer? The following command converts "06/21/2011" (the start of summer) to a date, and then subtracts the current date from that. It stores the result in the $result variable, and then accesses the TotalDays property.

PS > $result = [DateTime] "06/21/2011" - [DateTime]::Now
PS > $result.TotalDays
283.0549285662616

5 comments

  1. David "Makovec" Moravec Posted 17 days and 21 hours ago

    What about to change year to 2010. I know it will be also old in 101 days from now, but ... just idea.

  2. Kjartan Þór Kjartansson Posted 16 days and 6 hours ago

    Or even better to just say mm/dd/yyyy and give the date as an example

  3. Johannes Rössel Posted 16 days and 4 hours ago

    Or maybe yyyy-mm-dd here too, as mentioned previously in another comment as well.

  4. Clayton McKenzie Posted 15 days and 2 hours ago

    Is it worth mentioning that Powershell doesn't appear to pay any attention to date order set in the computers regional settings for [DATETIME] somewhere?

  5. Lee Holmes Posted 14 days and 13 hours ago

    David, Kjartan: Thanks - I updated it to 2011 so that it will be valid for at least a year after the book gets on the shelves. Johannes, Clayton: Thanks - there are several recipes that talk about the en-US parsing - for example, http://powershell.labs.oreilly.com/ch13.html#write_culture-aware_scripts.

Add a comment

Composable Commands

Whenever a command generates output, you can use a pipeline character (|) to pass that output directly to another command as input. If the second command understands the objects produced by the first command, it can operate on the results. You can chain together many commands this way, creating powerful compositions out of a few simple operations. For example, the following command gets all items in the Path1 directory and moves them to the Path2 directory:

2 comments

  1. Mark Schill Posted 17 days and 17 hours ago

    Maybe a brief comment about how objects can be passed through the pipeline as they happen instead of waiting for each step to complete??

  2. Lee Holmes Posted 14 days and 23 hours ago

    Thanks, I made this more clear in the intro to the Pipelines chapter.

Add a comment

Get-Item Path1\* | Move-Item -Destination Path2

You can create even more complex commands by adding additional cmdlets to the pipeline. In Example 3, “You can build more complex PowerShell commands by using pipelines to link cmdlets, as shown in this example with Get-Process, Where-Object, Sort-Object, and Format-Table”, the first command gets all processes running on the system. It passes those to the Where-Object cmdlet, which runs a comparison against each incoming item. In this case, the comparison is $_.Handles -ge 500, which checks whether the Handles property of the current object (represented by the $_ variable) is greater than or equal to 500. For each object in which this comparison holds true, you pass the results to the Sort-Object cmdlet, asking it to sort items by their Handles property. Finally, you pass the objects to the Format-Table cmdlet to generate a table that contains the Handles, Name, and Description of the process.

Example 3. You can build more complex PowerShell commands by using pipelines to link cmdlets, as shown in this example with Get-Process, Where-Object, Sort-Object, and Format-Table

PS > Get-Process |
>>     Where-Object { $_.Handles -ge 500 } |
>>     Sort-Object Handles |
>>     Format-Table Handles,Name,Description -Auto
>>

Handles Name     Description
------- ----     -----------
    588 winlogon
    592 svchost
    667 lsass
    725 csrss
    742 System
    964 WINWORD  Microsoft Office Word
   1112 OUTLOOK  Microsoft Office Outlook
   2063 svchost

Techniques to Protect You from Yourself

While aliases, wildcards, and composable pipelines are powerful, their use in commands that modify system information can easily be nerve-wracking. After all, what does this command do? Think about it, but don't try it just yet:

PS > gps [b-t]*[c-r] | Stop-Process

It appears to stop all processes that begin with the letters b through t and end with the letters c through r. How can you be sure? Let PowerShell tell you. For commands that modify data, PowerShell supports -WhatIf and -Confirm parameters that let you see what a command would do:

3 comments

  1. Aleksandar Nikolic Posted 17 days and 21 hours ago

    I'm not sure if this is the first time that you mention parameters (by name), but I will comment it here.

    A hyphen is not a part of parameter name.

    Ref. about_Parameters topic:

    "The parameters follow the cmdlet or function name and typically have the following form:

        -<parameter_name> <parameter_value>
    
    The name of the parameter is preceded by a hyphen (-), which signals to 
    Windows PowerShell that the word following the hyphen is a parameter and 
    not a value being passed to the cmdlet or function."
    

    So, according to this and PowerShell Help style guide, every time when you mention the name of the parameter in a text, a hyphen should be omitted.

  2. Lee Holmes Posted 15 days and 16 hours ago

    Thanks, Aleksandar. I know that's the official guidance of our help authors -- I tried that in the first edition, and it confused people in the context of the book.

  3. Aleksandar Nikolic Posted 15 days and 9 hours ago

    Interesting. Here is even easier to understand that you are talking about the parameters, because you are using different font for the name of the parameter which is not possible in the official Help. (Hmm... I've checked now and Bruce is using a hyphen as well in his "PowerShell in Action" book, and all parameter names are in lower case.) I would like to see these things more consistent.

Add a comment

PS > gps [b-t]*[c-r] | Stop-Process -whatif
What if: Performing operation "Stop-Process" on Target "ctfmon (812)".
What if: Performing operation "Stop-Process" on Target "Ditto (1916)".
What if: Performing operation "Stop-Process" on Target "dsamain (316)".
What if: Performing operation "Stop-Process" on Target "ehrecvr (1832)".
What if: Performing operation "Stop-Process" on Target "ehSched (1852)".
What if: Performing operation "Stop-Process" on Target "EXCEL (2092)".
What if: Performing operation "Stop-Process" on Target "explorer (1900)".
(...)

In this interaction, using the -WhatIf parameter with the Stop-Process pipelined command lets you preview which processes on your system will be stopped before you actually carry out the operation.

1 comment

  1. Aleksandar Nikolic Posted 17 days and 21 hours ago

    -whatif parameter --> -WhatIf parameter (or "WhatIf parameter", if you accept my suggestion to omit a hyphen).

Add a comment

Note that this example is not a dare! In the words of one reviewer:

Not only did it stop everything, but on Vista, it forced a shutdown with only one minute warning!

It was very funny though… At least I had enough time to save everything first!

Common Discovery Commands

While reading through a guided tour is helpful, I find that most learning happens in an ad hoc fashion. To find all commands that match a given wildcard, use the Get-Command cmdlet. For example, by entering the following, you can find out which PowerShell commands (and Windows applications) contain the word process.

PS > Get-Command *process*

CommandType     Name                     Definition
-----------     ----                     ----------
Cmdlet          Get-Process              Get-Process [[-Name] <Str...
Application     qprocess.exe             c:\windows\system32\qproc...
Cmdlet          Stop-Process             Stop-Process [-Id] <Int32...

To see what a command such as Get-Process does, use the Get-Help cmdlet, like this:

PS > Get-Help Get-Process

Since PowerShell lets you work with objects from the .NET Framework, it provides the Get-Member cmdlet to retrieve information about the properties and methods that an object, such as a .NET System.String, supports. Piping a string to the Get-Member command displays its type name and its members:

PS > "Hello World" | Get-Member

   TypeName: System.String

Name             MemberType            Definition
----             ----------            ----------
(...)
PadLeft          Method                System.String PadLeft(Int32 tota...
PadRight         Method                System.String PadRight(Int32 tot...
Remove           Method                System.String Remove(Int32 start...
Replace          Method                System.String Replace(Char oldCh...
Split            Method                System.String[] Split(Params Cha...
StartsWith       Method                System.Boolean StartsWith(String...
Substring        Method                System.String Substring(Int32 st...
ToCharArray      Method                System.Char[] ToCharArray(), Sys...
ToLower          Method                System.String ToLower(), System....
ToLowerInvariant Method                System.String ToLowerInvariant()
ToString         Method                System.String ToString(), System...
ToUpper          Method                System.String ToUpper(), System....
ToUpperInvariant Method                System.String ToUpperInvariant()
Trim             Method                System.String Trim(Params Char[]...
TrimEnd          Method                System.String TrimEnd(Params Cha...
TrimStart        Method                System.String TrimStart(Params C...
Chars            ParameterizedProperty System.Char Chars(Int32 index) {...
Length           Property              System.Int32 Length {get;}

Ubiquitous Scripting

PowerShell makes no distinction between the commands typed at the command line and the commands written in a script. Your favorite cmdlets work in scripts and your favorite scripting techniques (e.g., the foreach statement) work directly on the command line. For example, to add up the handle count for all running processes:

2 comments

  1. Andy Helsby Posted 5 days and 18 hours ago

    Sorry to be picky but this is not always true (and as a beginner I don't know why yet...) "get-mailboxstatistics| ft DisplayName,TotalItemSize,ItemCount" works on an Exchange server at the command line but does not work in a script. In a script you need "get-mailboxstatistics| ft DisplayName,TotalItemSize,ItemCount | out-string"

  2. Lee Holmes Posted 1 day and 17 hours ago

    This unfortunately happens at the command-line too: dir | Format-Table | Sort Name

    As to why, thanks for bringing this up. I've added additional comments to the Format-* recipes.

Add a comment

PS > $handleCount = 0
PS > foreach($process in Get-Process) { $handleCount += $process.Handles }
PS > $handleCount
19403

While PowerShell provides a command (Measure-Object) to measure statistics about collections, this short example shows how PowerShell lets you apply techniques that normally require a separate scripting or programming language.

In addition to using PowerShell scripting keywords, you can also create and work directly with objects from the .NET Framework that you may be familiar with. PowerShell becomes almost like the C# immediate mode in Visual Studio. Example 4, “Using objects from the .NET Framework to retrieve a web page and process its content” shows how PowerShell lets you easily interact with the .NET Framework.

Example 4. Using objects from the .NET Framework to retrieve a web page and process its content

PS > $webClient = New-Object System.Net.WebClient
PS > $content = $webClient.DownloadString("http://blogs.msdn.com/PowerShell/rss.aspx")
PS > $content.Substring(0,1000)
<?xml version="1.0" encoding="UTF-8" ?>
<?xml-stylesheet type="text/xsl" href="http://blogs.msdn.com/utility/FeedS
tylesheets/rss.xsl" media="screen"?><rss version="2.0" xmlns:dc="http://pu
rl.org/dc/elements/1.1/" xmlns:slash="http://purl.org/rss/1.0/modules/slas
h/" xmlns:wfw="http://wellformedweb.org/CommentAPI/"><channel><title>Windo
(...)

1 comment

  1. Claus Thude Nielsen Posted 9 days and 22 hours ago

    Maybe add in a short description of what $content.Substring(0,1000) does, it might not be clear to everyone.

Add a comment


Ad Hoc Development

By blurring the lines between interactive administration and writing scripts, the history buffer of PowerShell sessions quickly become the basis for ad-hoc script development. In this example, you call the Get-History cmdlet to retrieve the history of your session. For each of those items, you get its CommandLine property (the thing you typed) and send the output to a new script file.

PS > Get-History | Foreach-Object { $_.CommandLine } > c:\temp\script.ps1
PS > notepad c:\temp\script.ps1
(save the content you want to keep)
PS > c:\temp\script.ps1

1 comment

  1. Andy Helsby Posted 5 days and 18 hours ago

    May be worth explaining why you need the Foreach-object line (to get rid of the line numbers). It took me for ever to work out how to do this when I was doing some adhoc development to write a simple script and then was very frustrated when I couldn't easily save my output so thanks for this simple recipe. At this point i'd like to know a way to save the first line as a function/alias/cmdlet that I can use such as save-history filename so I don't have to remember that long command eachtime. Could this be included here (or at least linked in the book as a sidenote?

Add a comment

Note

If this is the first time you've run a script in PowerShell, you will need to configure your Execution Policy. For more information about selecting an execution policy, see the section called “Enable Scripting Through an Execution Policy”.

For a recipe that goes into more detail about saving your session history into a script, see the section called “Program: Create Scripts From Session History”.

Bridging Technologies

We've seen how PowerShell lets you to fully leverage the .NET Framework in your tasks, but its support for common technologies stretches even further. As Example 5, “Working with XML content in PowerShell” (continued from Example 4, “Using objects from the .NET Framework to retrieve a web page and process its content”) shows, PowerShell supports XML:

Example 5. Working with XML content in PowerShell

PS > $xmlContent = [xml] $content
PS > $xmlContent

xml                       xml-stylesheet            rss
---                       --------------            ---
version="1.0" encoding... type="text/xsl" href="... rss

PS > $xmlContent.rss

version : 2.0
dc      : http://purl.org/dc/elements/1.1/
slash   : http://purl.org/rss/1.0/modules/slash/
wfw     : http://wellformedweb.org/CommentAPI/
channel : channel



PS > $xmlContent.rss.channel.item | select Title

title
-----
CMD.exe compatibility
Time Stamping Log Files
Microsoft Compute Cluster now has a PowerShell Provider and Cmdlets
The Virtuous Cycle: .NET Developers using PowerShell
(...)

2 comments

  1. Mark Schill Posted 17 days and 17 hours ago

    Mention that this is a continuation of the work from Example 4?

  2. Andy Helsby Posted 5 days and 18 hours ago

    $xmlContent is also likely to provide more content - the xml and xml stylesheet are likely to contain information such as below PS > $xmlContent

    xml xml-stylesheet rss


    version="1.0" encoding="UTF-8" type="text/xsl" href="http://blogs.m... rss

Add a comment


PowerShell also lets you work with Windows Management Instrumentation (WMI):

PS > Get-WmiObject Win32_Bios


SMBIOSBIOSVersion : ASUS A7N8X Deluxe ACPI BIOS Rev 1009
Manufacturer      : Phoenix Technologies, LTD
Name              : Phoenix - AwardBIOS v6.00PG
SerialNumber      : xxxxxxxxxxx
Version           : Nvidia - 42302e31

or, as Example 6, “Working with Active Directory in PowerShell” shows, Active Directory Service Interfaces (ADSI):

Example 6. Working with Active Directory in PowerShell

PS > [ADSI] "WinNT://./Administrator" | Format-List *


UserFlags                  : {66113}
MaxStorage                 : {-1}
PasswordAge                : {19550795}
PasswordExpired            : {0}
LoginHours                 : {255 255 255 255 255 255 255 255 255 255 255
                             255 255 255 255 255 255 255 255 255 255}
FullName                   : {}
Description                : {Built-in account for administering the compu
                             ter/domain}
BadPasswordAttempts        : {0}
LastLogin                  : {5/21/2007 3:00:00 AM}
HomeDirectory              : {}
LoginScript                : {}
Profile                    : {}
HomeDirDrive               : {}
Parameters                 : {}
PrimaryGroupID             : {513}
Name                       : {Administrator}
MinPasswordLength          : {0}
MaxPasswordAge             : {3710851}
MinPasswordAge             : {0}
PasswordHistoryLength      : {0}
AutoUnlockInterval         : {1800}
LockoutObservationInterval : {1800}
MaxBadPasswordsAllowed     : {0}
RasPermissions             : {1}
objectSid                  : {1 5 0 0 0 0 0 5 21 0 0 0 121 227 252 83 122
                             130 50 34 67 23 10 50 244 1 0 0}

or, as Example 7, “Working with COM objects in PowerShell” shows, even scripting traditional COM objects:

Example 7. Working with COM objects in PowerShell

PS > $firewall = New-Object -com HNetCfg.FwMgr
PS > $firewall.LocalPolicy.CurrentProfile


Type                                         : 1
FirewallEnabled                              : True
ExceptionsNotAllowed                         : False
NotificationsDisabled                        : False
UnicastResponsesToMulticastBroadcastDisabled : False
RemoteAdminSettings                          : System.__ComObject
IcmpSettings                                 : System.__ComObject
GloballyOpenPorts                            : {Media Center Extender Serv
                                               ice, Remote Media Center Ex
                                               perience, Adam Test Instanc
                                               e, QWAVE...}
Services                                     : {File and Printer Sharing,
                                               UPnP Framework, Remote Desk
                                               top}
AuthorizedApplications                       : {Remote Assistance, Windows
                                               Messenger, Media Center, T
                                               rillian...}

Namespace Navigation Through Providers

Another avenue PowerShell provides for working with the system is providers. PowerShell providers let you navigate and manage data stores using the same techniques you already use to work with the filesystem, as illustrated in Example 8, “Navigating the filesystem”.

1 comment

  1. Jeff Poling Posted 16 days and 16 hours ago

    maybe a little more detail about what a provider is?

Add a comment


This also works on the registry, as shown in Example 9, “Navigating the registry”:


Or even the machine's certificate store, as Example 10, “Navigating the certificate store” illustrates.


Much, Much More

As exciting as this guided tour was, it barely scratches the surface of how you can use PowerShell to improve your productivity and systems management skills. For more information about getting started in PowerShell, see Chapter 1, The Windows PowerShell Interactive Shell, The Windows PowerShell Interactive Shell.

You must sign in or register before commenting
*
*
*
*
*

Atom Icon Comments on this page or Comments on the whole book.