Quantcast
Channel: PowerShell – CHUVASH.eu
Viewing all articles
Browse latest Browse all 20

A PowerShell one liner

$
0
0

PowerShell is powerful. You can write concise, well formulated, functional-style code. Recently I got the following quiz:

You’ve got $100. You have to buy exactly 100 animal, at least 1 dog, 1 cat and 1 mouse. 1 dog costs $15, 1 cat costs $1, 1 mouse costs $0.25.

There can be  many ways to solve it. But look at this one line solution. It is quite impressive what you can do with PowerShell

1..98 | % {
    $dog = $_
    1..98 | % {
      $cat = $_
      @{
        "Dog" = $dog
        "Cat" = $cat
        "Mouse" = 100 - $dog -$cat
      }
    }
  } | ? {
      $_.Mouse -gt 0
  } | ? { $_.Dog * 15 + $_.Cat * 1 + $_.Mouse * 0.25 -eq 100 }

This solution uses ranges, dynamic objects (PSObject), nested for loops, implicit returns and advanced filtering. All that is is out-of-the-box PowerShell.



Viewing all articles
Browse latest Browse all 20

Trending Articles