Get-ChildItem is not dir!

Here is a simple but practical tip from the trenches. If you made the switch and are using PowerShell as your main console, you may have noticed that the dir command can be rather sluggish in large directories. While an attempt was made to make the transition to native PS CmdLets easier by making “dir” an alias for Get-ChildItem, there is an important syntax difference.

If you are looking for a particular (set of) files, the trick is to split the full file name(s) into a path and file specification. To illustrate, just run the following commands and notice the performance difference:

PS C:>dir c:windowssystem32*.ini

PS C:>dir c:windowssystem32 *.ini

The second command is much faster because it uses the filtering mechanism from the file system provider. I have been burned by this many times and I suspect that others have too. Several scripts performed dramatically better after making this change. Incidentally, this is why PowerTab‘s (yes, you really SHOULD use this!) file system completion is pretty slow compared to that of the good old cmd prompt.

This is another good example of why it pays to scrutinize the PS help system:

PS C:>help Get-ChildItem -detailed

[...]
PARAMETERS
    -path <string[]>
        Specifies a path to one or more locations. Wildcards are permitted. The default location is the current directo
        ry (.).

    -include <string[]>
        Retrieves only the specified items. The value of this parameter qualifies the Path parameter. Enter a path elem
        ent or pattern, such as “*.txt”. Wildcards are permitted.
[...]

 

Arnoud

 

One thought on “Get-ChildItem is not dir!

  1. I think you were thinking about filter and not include. If you do the same example you used but using -include, you don’t get any results at all. But it works as you said if you use -filter. Filter is also positionally the second parameter for Get-ChildItem with path being the first.

    Nice comparison though, I hadn’t realized the speed difference between the 2 ways before.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>