4 responses to “Fibonacci Sequence … in PowerShell”

  1. Andy

    I like the pipeline method. Very cool. You can also use double variable assignment.

    http://www.get-powershell.com/
    http://getpowershell.wordpress.com/2008/01/24/fibonacci-series-in-powershell/

  2. Jeffery Hicks

    This only gives you the last number in the sequence. Here’s a solution I came up with awhile ago (I’m very geeky for stuff like this) that uses recursion so you get the full sequence:

    Function Get-Fibonacci {
    Param([int]$n=0)

    if ($n -eq 0) {$result = 0}
    elseif ($n -eq 1) { $result =1}
    else {

    $result=(Get-Fibonacci($n-1)) + (Get-Fibonacci ($n-2))
    }

    write $result

    }

    for ($x=0;$x -le 11;$x++) {
    Get-Fibonacci $x
    }

  3. Jeffery Hicks

    I just found this mentioned on a related blog from Bruce’s book (I must have not gotten that far yet) which is even better. This will display the sequence up to 1000

    $c=$p=1; while ($c -lt 1000) { $c; $c,$p = ($c+$p), $c }