Scripting Games – what’s wrong with this

I noticed code like this in quite a few entries in for Event 1

Get-ChildItem -path C:\Application\log -Recurse -Filter *.log | Where-Object{$_.LastWriteTime -lt [DateTime]::Now.Subtract([TimeSpan]::FromDays(90))} | ForEach-Object {…}

From the title it should be obvious that there’s something I don’t like. 

The where-object re-calculates the date to test for EVERY object on the pipeline.

That’s not efficient.

Put the calculation outside your pipeline

$testdate = [DateTime]::Now.Subtract([TimeSpan]::FromDays(90))


$testdate = (get-date).AddDays(-90)

which I personally think is simpler

Your pipeline then becomes

Get-ChildItem -path C:\Application\log -Recurse -Filter *.log | Where-Object{$_.LastWriteTime –lt $testdate} | ForEach-Object {…}

Much simpler and more efficient.

I wonder if putting the calculation into the pipeline is part of the almost religious fervour surrounding the “one-liner”.  if you can sensibly put your code into 1 line – read one pipeline because that’s what we’re really doing – then do so. But don’t make it more inefficient as a consequence.

This entry was posted in Powershell, Powershell Basics, Scripting Games. Bookmark the permalink.

Leave a Reply

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

You are commenting using your 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