Windows IT Pro is the leading independent community for IT professionals deploying Microsoft Windows server and client applications and technologies.
  
  
  Advanced Search 


July 2009

Emulating the Dir Command in PowerShell

Try this handy Windows PowerShell script that mimics the way dir works in Cmd.exe
RSS
Subscribe to Windows IT Pro | See More Scripting Articles Here | Reprints | Or get the Monthly Online Pass—only $5.95 a month!
SideBar    Understanding Bitmap Values

Download the Code Here

Executive Summary:
The Windows PowerShell Get-ChildItem cmdlet uses the dir alias and is similar to Cmd.exe's dir command, although the PowerShell command doesn't have all the same features . The D.ps1 script rectifies this disparity by emulating dir's most useful features in a PowerShell script.


Using Windows PowerShell is a paradigm-shifting experience for Windows users who are accustomed to the Cmd.exe command shell. PowerShell is much more powerful and flexible, but most Cmd.exe commands don't have direct PowerShell equivalents. For example, PowerShell has a default dir alias that runs the Get-ChildItem cmdlet, but Get-ChildItem doesn't behave exactly the same as Cmd.exe's dir command.

Because dir is probably the command I use most frequently in Cmd.exe, I found myself missing some of dir's features when working in PowerShell—in particular, its /a (select attributes) and /o (sort order) parameters. Table 1 shows some example Cmd.exe dir commands and their PowerShell equivalents. As you can see, the PowerShell commands are all longer—and in many cases more complex—than the equivalent dir commands in Cmd.exe. To improve my productivity at the PowerShell command line, I wrote a script, D.ps1, which emulates a number of dir's most useful features.

Introducing D.ps1
You can download D.ps1 by clicking the Download the Code Here button at the top of this page. Table 2 describes D.ps1's command-line parameters. The main difference between using D.ps1 and using dir in Cmd.exe is that you use a dash (-) instead of a forward slash (/) for the parameters. All of the script's parameters are optional. If you run the script without parameters, it lists the contents of the current directory.

D.ps1 counts the number of files and directories, totals the lengths of the files, and reports them at the end of its output, as dir does. Figure 1 shows an example of D.ps1's output that displays the JScript script files in the current directory, sorted by date. Note that D.ps1's output doesn't include the displayed directory's path as Get-ChildItem and the dir command do. D.ps1 also displays each file's attributes, which Get-ChildItem does but dir doesn't do. Table 3 shows some sample D.ps1 commands and a description of each command.

By default, D.ps1 outputs formatted strings rather than file system objects. If you want to output objects or you want to list items from a location other than the file system, you must specify the -defaultoutput parameter, as noted in Table 2. If the current path isn't in the file system (e.g., HKCU:\) and you don't specify a path to list, D.ps1 outputs an error unless you use -defaultoutput.

The script is composed of a param statement, which defines the script's command-line parameters, and six functions: usage, iif, get-attributeflags, get-orderlist, get-providername, and main. The last line of the script executes the main function, which calls the other functions as needed.

The usage and iif Functions
If the -help parameter is present on the command line, the main function executes the usage function, which callout A in Listing 1 shows. The usage function simply outputs a usage message and ends the script with the exit statement.

The iif function provides a shortcut for the following frequently used syntax:

if (condition) {
$variable = truevalue
} else {
$variable = falsevalue
}

By using the iif function, you can write this instead:

$variable = iif { condition } { truevalue } { falsevalue } 

Callout B in the listing shows the iif function. The function uses three script blocks as parameters. It executes the first script block ($expr); if the result is true, the script executes the second script block; otherwise, it executes the third script block.

The get-attributeflags Function
The main function uses the get-attributeflags function to convert the -attributes parameter's argument (a string containing a list of file attributes to include or exclude) into two bitmap values. If you aren't familiar with bitmap values, see the sidebar "Understanding Bitmap Values."

The get-attributeflags function, which you can see at callout C, first creates a hash table that contains the attribute characters and their associated .NET bit mask values. It then builds a string based on the hash table's keys, iterates each character in the attribute string, and uses the switch statement to decide whether to enable or disable bits in the returned values. If the attribute character isn't a dash or a valid attribute character, the function throws an error, ending the script. The last line of the get-attributeflags function returns the two bitmap values to the main function; these values are used later in the script.

   Previous  [1]  2  3  Next 


Top Viewed ArticlesView all articles
Command Prompt Tricks

One reader shares his tip for setting up the command prompt to reflect a remote path. ...

2009 Windows IT Pro Editors' Best and Community Choice Awards

Picking a favorite product from an impressive crowd of competitive offerings is never an easy task, and such was the case with our Editors' Best and Community Choice awards this year. ...

WinInfo Short Takes: Week of November 23, 2009

An often irreverent look at some of the week's other news, including some post-PDC some soul searching, a Google Chrome OS announcement and a Microsoft response, Windows 7 off to a supposedly strong start, the Jonas Brothers and Xbox 360, and so much more ...


Related Articles Q. How can I launch a Windows PowerShell instance to run a command from a cmd.exe prompt?

Iterating Through Collections with PowerShell's foreach Loops

PowerShell 101, Lesson 4

PowerShell 101, Lesson 3

Scripting Whitepapers From Development to Production: Streamlining SharePoint Deployment with DocAve Deployment Manager

Related Events PowerShell 201 - eLearning Series with Paul Robichaux

7 Ways To Get More From Your SharePoint Deployment Now

Check out our list of Free Email Newsletters!

Scripting eBooks Keeping Your Business Safe from Attack: Encryption and Certificate Services

Best Practices for Managing Linux and UNIX Servers

Building an Effective Reporting System

Related Scripting Resources Introducing Left-Brain.com, the online IT bookstore
Looking for books, CDs, toolkits, eBooks? Prime your mind at Left-Brain.com

Discover Windows IT Pro eLearning Series!
Clear & detailed technical information and helpful how-to's, all in our trademark no-nonsense format


Windows IT Pro Home Register FAQ for Windows WinInfo News
Europe Edition About Us Contact Us/Customer Service Media Kit Affiliates / Licensing  
SQL Server Magazine Office & SharePoint Pro DevProConnections IT Job Hound
Left-Brain.com Technology Resource Directory asp.netPRO ITTV Windows SuperSite 
 
 Windows IT Pro is a Division of Penton Media Inc.
 © 2009 Penton Media, Inc. Terms of Use | Privacy Statement