Getting Folders by Prefix

by Dec 6, 2013

Did you know that Group-Object can easily group elements by custom criteria? Here's a line that groups folders by their first three letters:

Get-ChildItem -Path C:\Windows -Directory | 
   Group-Object -Property { $_.Name.PadRight(3).Substring(0,3)} 

And with little additional effort, you can create a hash table that uses these three letters as a key:

$lookup = Get-ChildItem -Path $env:windir -Directory  | 
   Group-Object -Property { $_.Name.PadRight(3).Substring(0,3).ToUpper()} -AsHashTable -AsString

$lookup.Keys 

So now it is really trivial to get all folders that, let's say, start with "SYS":

And why is that useful? Some companies use folder prefixes for business units. With this technique, it's easy to bundle all business unit folders together – you could then sum up their total storage space in a second step and create automatic reporting.

Twitter This Tip! ReTweet this Tip!