The comment about how awkward it is in PowerShell to filter out folders with Get-ChidlItem, or its alias dir, came up the other day on Twitter. I'll be the first to admit that running a DIR command and wanting to skip folders, or perhaps you only want top level folders, is more cumbersome than we would like in PowerShell v2. In PowerrShell v3 this has been addressed but for now we're stuck with expressions like this:
ManageEngine ADManager Plus - Download Free Trial
Exclusive offer on ADManager Plus for US and UK regions. Claim now!
[cc lang="PowerShell"]
dir c:\work -rec | where {!$_.PSIsContainer} | group extension | sort count
[/cc]
If you find yourself frequently performing this type of filtering in the shell, here's a tip that can save a little typing. Create these two functions:
[cc lang="PowerShell"]
function IsDir {process {$_ | Where {$_.PSIsContainer}}}
function NotDir {process {$_ | Where {!$_.PSIsContainer}}}
[/cc]
These are so simple I'm not even going to include a text download. You can call them whatever you want. The functions are written as filtering functions, notice the use of Process script block. In short, these are wrappers for the standard Where-Object filter we're used to using. But now I can do this:
[cc lang="PowerShell"]
dir c:\work -rec | notdir | group extension | sort count
[/cc]
Or perhaps this:
[cc lang="PowerShell"]
dir c:\work | isdir | Select FullName,@{Name="Size";Expression={(dir $_.fullname -rec | notdir | measure length -sum).sum}} | format-table -auto
[/cc]
If you find yourself needing this every day, put the function definitions in your profile. You can use this same technique for other common filters you tend to use often. What else can you come up with?
Love this tip unquestionably ….
But ok, what about the v1 scenario for filtering?
–
Does one have hope for addressing the question of – ‘simplicity on the far side of complex’ ? Or were you waiting for someone to ask the question, oh Kung Fu master?
Signed,
Grasshopper 🙂
I don’t have a system with PowerShell v1 handy but I have no reason to think this won’t work there.
Confirmed on v1. Sometimes we have to use what we’re given until we get what we need. Thanks. 8Δ)
Yep, confirmed for v1.
Sometimes we use what we’re given until we get what we need.
Thanks! 8Δ)