PowerShell for Windows Admins

Sep 15 2013   3:44AM GMT

PowerShell whimsy with arrays

Richard Siddaway Richard Siddaway Profile: Richard Siddaway

I was thinking about the Christmas song – 12 days of Christmas and wondering just how many presents were delivered. Don’t ask why!

So I decided to work it out.

$days = 12
$presents = 1..$days

$total = 0
0..($days-1) | foreach {
$total += $presents[$_] * $presents[(-1 * $presents[$_] )]
}
$total

You start with 12 days & create an array containing the values 1 to 12

Set the total to 0 & loop through the days. Because array indices start at 0 you need the range 0-11 which you can calculate as 0..($days-1)

The total number of presents delivered of a type is the number of things 1 partridge, 2 turtle doves etc multiplied by the number of times its delivered 12, 11, 10 etc

The number of presents of a particular type is from the array $presents[$_]. The days delivered is found by getting an inverse relationship into the array. So present 1 delivered 12 times which is value of last element; present 2 delivered 11 times which is next to last element etc.

Now the point of the post is to show you that you can access the last element of an array using an index of –1; the next to last using –2 and so on.

As we want to calculate this we end up with taking the value of the array for that point and multiplying by –1 to get the value we need fo r the multiplication

$presents[(-1 * $presents[$_] )]

Add the calculated values together and you get the total number of presents delivered.

I’ve deliberately put more () into this than needed to make the logic easier to follow.

 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: