Dr. Dobb's is part of the Informa Tech Division of Informa PLC

This site is operated by a business or businesses owned by Informa PLC and all copyright resides with them. Informa PLC's registered office is 5 Howick Place, London SW1P 1WG. Registered in England and Wales. Number 8860726.


Channels ▼
RSS

.NET

Windows PowerShell


Real-World Examples in PowerShell

One of the most effective ways of highlighting the flexibility and usability of PowerShell is by example. The following two examples focus on simple handling of directory listings. However the principles demonstrated here will be applicable to other areas of PowerShell.

Example 1: Handling Directories using PowerShell

This example addresses some practical examples for using PowerShell to list the contents of directories. Consider if you want to simply list all files in a directory and below that have been modified within the past week. You could resort to "walking" the directory structure and try to capture the output in DOS. Or, you might use a number of other creative approaches. With PowerShell, the solution is efficient and elegant-two cmdlets work collaboratively (dir and where) using pipes.

dir . -r | Where { $_.LastWriteTime -ge (Get-Date).AddDays(-7) } | Select name

In reviewing this code, we see that objects with properties-not text-is being piped between commands using the pipe (|). First, a recursive directory listing is retrieved (using the -r flag). The dir cmdlet produces a System.IO.FileInfo object for each located item, based on the parameters passed. Each time this object is presented, it is piped to the Where cmdlet.

The Where cmdlet allows a script block; this is defined between the two curly braces. The $_ is a PowerShell automatic variable which has the current object in the pipeline (a System.IO.FileInfo outputted from the dir cmdlet). To access the contents of the date property, the conventional object notation is used: $_.LastWriteTime. The purpose of LastWriteTime is used to restrict the list to only those files modified within the last seven days. Finally, the name of the file is displayed. All this is accomplished in one line of code.

A similar command-only restricting by a fixed date and a filetype of .cs-would be:

dir . -Recurse *.cs| Where {$_.LastWriteTime -gt "11/14/2006"}

Note in this example that the -gt represents the greater-than comparison operator. The LastWriteTime is of type System.DateTime, so when the greater than comparison is done, PowerShell coerces the .LastWriteTime and String for us to be compared. Note also that the mathematical greater-than symbol ">" cannot be used; PowerShell interprets that character as a command to redirect the output.

[Click image to view at full size]

Example 2: Formatting Directory Outputs using PowerShell

Taking the previous example one step further, we can also define the format of the output by using the Sort-Object and Format-Table cmdlets. The Format-Table cmdlet trims down the verbose data. The -AutoSize parameter automatically adjusts the contents of each column. We can also define the properties we wish to be printed-specifically each file's LastWriteTime and Name.

dir . -Recurse *.cs| Where {$_.LastWriteTime -gt "11/12/2006"} | |
Format-Table -AutoSize LastWriteTime, Name

[Click image to view at full size]

We can also use wildcards when providing the properties to Format-Table such as *Time. This will display any property that ends with the letters "Time." This will produce a table with CreationTime, LastAccessTime and LastWriteTime as shown in the following screenshot.

[Click image to view at full size]

Notice the retrieved data is in random order. By inserting a pipe to the Sort-Object (between the Where and Format-Table) and adding the LastWriteTime as a parameter, we can sort the files by when the file was last written.

dir . -Recurse *.cs| Where {$_.LastWriteTime -gt "11/12/2006"} |
Sort LastWriteTime | Format-Table -AutoSize LastWriteTime, Name

[Click image to view at full size]

To see the table in descending time order, add the -Descending parameter to the sort cmdlet.

dir . -Recurse *.cs| Where {$_.LastWriteTime -gt "11/12/2006"} |
Sort LastWriteTime -Descending | Format-Table -AutoSize LastWriteTime, Name

To review, PowerShell shows its strengths by being able to pipe output through multiple commands to achieve the desired output.


Related Reading


More Insights






Currently we allow the following HTML tags in comments:

Single tags

These tags can be used alone and don't need an ending tag.

<br> Defines a single line break

<hr> Defines a horizontal line

Matching tags

These require an ending tag - e.g. <i>italic text</i>

<a> Defines an anchor

<b> Defines bold text

<big> Defines big text

<blockquote> Defines a long quotation

<caption> Defines a table caption

<cite> Defines a citation

<code> Defines computer code text

<em> Defines emphasized text

<fieldset> Defines a border around elements in a form

<h1> This is heading 1

<h2> This is heading 2

<h3> This is heading 3

<h4> This is heading 4

<h5> This is heading 5

<h6> This is heading 6

<i> Defines italic text

<p> Defines a paragraph

<pre> Defines preformatted text

<q> Defines a short quotation

<samp> Defines sample computer code text

<small> Defines small text

<span> Defines a section in a document

<s> Defines strikethrough text

<strike> Defines strikethrough text

<strong> Defines strong text

<sub> Defines subscripted text

<sup> Defines superscripted text

<u> Defines underlined text

Dr. Dobb's encourages readers to engage in spirited, healthy debate, including taking us to task. However, Dr. Dobb's moderates all comments posted to our site, and reserves the right to modify or remove any content that it determines to be derogatory, offensive, inflammatory, vulgar, irrelevant/off-topic, racist or obvious marketing or spam. Dr. Dobb's further reserves the right to disable the profile of any commenter participating in said activities.

 
Disqus Tips To upload an avatar photo, first complete your Disqus profile. | View the list of supported HTML tags you can use to style comments. | Please read our commenting policy.