PowerShell for Windows Admins

Jun 12 2013   3:31PM GMT

Scripting Games – what’s wrong with this



Posted by: Richard Siddaway
Tags:
PowerShell
Scripting Games

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))

or

$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.

 Comment on this Post

 
There was an error processing your information. Please try again later.
Thanks. We'll let you know when a new response is added.
Send me notifications when other members comment.

REGISTER or login:

Forgot Password?
By submitting you agree to receive email from TechTarget and its partners. If you reside outside of the United States, you consent to having your personal data transferred to and processed in the United States. Privacy

Forgot Password

No problem! Submit your e-mail address below. We'll send you an e-mail containing your password.

Your password has been sent to: