Batch to Powershell: dir /s

I often go looking for a file in batch, aka

c:\Program Files (x86)>dir /s fsi*
     Volume in drive C has no label.
     Volume Serial Number is 8EDE-D64E

     Directory of c:\Program Files (x86)\Microsoft F#\v4.0

    03/19/2010  02:02 PM           230,216 Fsi.exe
    09/30/2009  08:08 PM               158 Fsi.exe.config
                   2 File(s)        230,374 bytes
Unfortunately this doesn't 'just work' in powershell. A quick search on the internet shows in powershell 'dir /s' becomes 'dir -r', but the following doesn't work either:
PS C:\Program Files (x86)> dir -r fsi*
PS C:\Program Files (x86)>
What's going on? Let's check the help:
PS C:\Program Files (x86)> help dir

NAME
    Get-ChildItem

SYNOPSIS
    Gets the items and child items in one or more specified locations.


SYNTAX
    Get-ChildItem [[-Path] ] [[-Filter] ] [-Exclude ] [-For
    ce] [-Include ] [-Name] [-Recurse] [-UseTransaction] []

    Get-ChildItem [-LiteralPath]  [[-Filter] ] [-Exclude ]
    [-Force] [-Include ] [-Name] [-Recurse] [-UseTransaction] []

Ahh, path and filter are two separate arguments in powershell. This means we get 2 choices.

A) Pass a path to the dir command (pass ‘.’ for current directory):

PS C:\Program Files (x86)> dir . fsi* -r

    Directory: C:\Program Files (x86)\Microsoft F#\v4.0


Mode                LastWriteTime     Length Name
----                -------------     ------ ----
-a---         3/19/2010   2:02 PM     230216 Fsi.exe
-a---         9/30/2009   8:08 PM        158 Fsi.exe.config
PS C:\Program Files (x86)>
B) Explicitly pass the -filter argument name (which we can abbreviate to -fi)
PS C:\Program Files (x86)> dir -r -fi fsi*


    Directory: C:\Program Files (x86)\Microsoft F#\v4.0


Mode                LastWriteTime     Length Name
----                -------------     ------ ----
-a---         3/19/2010   2:02 PM     230216 Fsi.exe
-a---         9/30/2009   8:08 PM        158 Fsi.exe.config    
PS C:\Program Files (x86)>

OK you’re thinking who cares, I can still do dir /s faster in batch? Ah, but you can’t do this:

 PS C:\Program Files (x86)> dir -r -fi fsi* | Where-Object {$_.Length -gt 200KB}


    Directory: C:\Program Files (x86)\Microsoft F#\v4.0


Mode                LastWriteTime     Length Name
----                -------------     ------ ----
-a---         3/19/2010   2:02 PM     230216 Fsi.exe
PS C:\Program Files (x86)>

Have fun, and remember read the docs when things don’t work as you’d expecxt:)

Comments

Sriram Krishnan said…
This annoys me in PS everytime. I have too much muscle memory to unlearn 'dir /s' :)

Popular posts from this blog

Finding CLR exceptions without visual studio

Why do I keep getting exception code e0434352?

Powershell script to enable windows to capture localhost traffic in wireshark