Share via


Happy Holidays - Festive Fun!

DISCLAIMER: my idea of fun and your idea of fun may well differ!

Ho, Ho, Ho!

Here's some PowerShell frolics I recently had with a customer. How we laughed!

The task - take the contents of a log file and reverse it with a loop. Oh, the joy!

Here's what I came up with:

$log = get-content .\20130902134204_GPO_Import.log

$i = $log.count

for ($i; $i -ge 0; $i--) {

Write-Output $log[$i]

}

 

Here's what my customer came up with

$log = get-content .\20130902134204_GPO_Import.log

$i = $log.count

do {

Write-Output $log[$I]

$i--

}

until ($i -eq -1)

 

Pretty standard stuff, don't you agree? We wanted to see who was fastest... cometh the hour, cometh Measure-Command!

 

Well, I won that one by 6 milliseconds!

Next, how to make the loop faster? My customer hit upon the idea of using the format operator (-f)... good thinking!

Measure-Command -Expression {

$i = $log.count - 1

for ($i; $i -ge 0; $i--) {

"{$i}" -f $log

}

}

 

 

Wow, that's four times as fast!

Now, forget all that looping nonsense and let's use a static method:

Measure-Command -Expression {

[array]::reverse($log)

$log

}

 

Scintillating!

 

Peace, brethren and sistren...