Determining unique file extensions recursively using Powershell

I thought that this would be an easy task for Powershell: definitely a one-liner. How would I do it though? I’d start with Get-ChildItem, expose an extension property, do some piping, no problem. Yet I drew a blank on the details. Fortunately the Scripting Guy had it all worked out here, just like this:

Get-ChildItem C:\Scripts | Select-Object Extension | Sort-Object Extension | Get-Unique

Thanks Scripting Guy! But wait, I wanted to run it recursively so I just added a -Recurse and lo and behold: no results! What in the binaries is going on here?

Going back to the article, I learned that Get-Unique is not doing what I thought it might do. It is comparing objects rather than strings. So I had to add an -AsString parameter comme ├ža:

Get-ChildItem C:\Scripts -Include *.* -Recurse | Select-Object Extension | Sort-Object Extension | Get-Unique -AsString

That got me closer, except for one more tiny little detail. There were lowercase and uppercase extensions causing duplicates. I needed a case insensitive unique list. I had to ditch the Get-Unique cmdlet and go back to the Sort-Object since it had a -Unique parameter.

Get-ChildItem c:\Scripts -Include *.* -Recurse | Select-Object Extension | Sort-Object -Property Extension -Unique

Now we are back in business!

About these ads
Tagged with:
Posted in Development
4 comments on “Determining unique file extensions recursively using Powershell
  1. Guido Kroon says:

    Sadly, this also includes folder names with dots. Not sure if it’s relevant, but I’m using PowerShell v3.0 on Windows 8 x64

  2. @Guido:
    You can add the following “where” clause to exclude folders:

    gci .\ -Include *.* -Recurse | Where { ! $_.PSIsContainer } | Select-Object Extension | Sort-Object -Property Extension -Unique

  3. Chiropractor says:

    I really like your blog.. very nice colors & theme.
    Did you make this website yourself or did you hire someone
    to do it for you? Plz respond as I’m looking to construct my own blog and would like to find out where u got this from. appreciate it

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

%d bloggers like this: