Author Posts

October 25, 2013 at 1:53 pm

All,
I feel like I should know this one however it is driving me crazy. And scouring the interweb isn't helping.

in powershell 3.0 what is the correct syntax for -filter param in get-child.

traditionally I would just write a get-child item filter like this


get-childitem c:\customerlogs -r |where {$_.creationtime -lt (get-date).adddays(-30)}

however according to the powershell MVA video's its most efficient to do the filter as far to the left as possible. Therefor I've been trying to use the creation time property with the -filter param. But powershell keeps telling me to suck it.
I've been googling my fingers off and can't find an example of filter being used with creationtime
here is what I would intuitively write for a filter


get-childitem c:\customerlogs -r -filter {(creationtime -lt (get-date).adddays(-30))}

I don't get an error it just doesn't return anything. I've tried a million different syntax permutation to no avail.
Any help would be appreciated. I know this should be basic stuff but its driving me nuts.

October 25, 2013 at 2:19 pm

Get-ChildItem's -filter parameter isn't a replacement for Where-Object.

Where-Object takes a -FilterScript (to use the full parameter name), which is any arbitrary script that can return True or False. The -Filter param of Get-ChildItem, as far as I know, only compares against the Name of the child items. You can't use -Filter against creation time, in short.

If you look at the help for -Filter, you'll see it accepts [string], meaning just a basic, simple string with some wildcards. It doesn't accept [ScriptBlock], which is what you've fed it.

It *IS* more efficient to "filter left." However, you can't always do so and get 100% flexibility on WHAT you can filter. E.g., using -Filter vs. Where-Object is better if you're filtering ON THE NAME – since that's what -Filter runs against.

Almost all the time, a -Filter parameter's value gets passed to the underlying technology (e.g., the FileSystem in your case), which means EVERY -Filter param ends up being different. Get-WmiObject's -Filter takes a string, but it must be a valid WMI Query Language WHERE expression (without the word "WHERE" in it, basically). Get-ADUser has a -Filter, too – it takes a couple of different permutations, but still gets processed at the DC so has some limits on what it'll be able to do.

October 25, 2013 at 2:48 pm

Dang should have payed attention to input value in the help file. Jason and Jeffery beat that horse to death in the intro to powershell 3.0 course.
Thanks for the quick response Don!