function interprets negative integers as a string instead of integers

function interprets negative integers as a string instead of integers

function Get-Factorial ($x) {
    if($x -isnot [int]){
       return "please enter an integer"
    }
    if ($x -eq 0) {
        return 1
    }
             return $x * (Get-Factorial($x - 1))
}

get-factorial -2 returns an error, but get-factorial (-2) works.

 

the only way to avoid the issue is to put the negative integer in a parenthesis, but I’m trying to avoid that.

 

You haven’t declared a type for the parameter, so PowerShell uses whatever it can. In this case, a lot of things in the parameter binder will register as strings if you enter them without parentheses.

However, its conversion logic is pretty sound, so if you in fact simply omitted that type check, it would run… but there are other pitfalls.

https://gist.github.com/vexx32/6b3e7350f24106c7c1599cca857bb2e7

 

I’m trying to have it accept negative integers, not reject them. AFAIK, in your examples, negative integers don’t work.

If you’re looking only for negative integers, I believe you can simply reverse the parameter definition from Joel’s example.

[pre]
[ValidateRange([int]::minValue,0)]
[/pre]

If you pass a negative integer to this function, it will recurse until it overflows (or underflows, I guess). Make sure you add proper handling for that first, but yes you can omit the validation attribute to allow those as well.

Have a read of this…

Understanding Numbers in PowerShell
https://devblogs.microsoft.com/scripting/understanding-numbers-in-powershell

Also, as a point of note:
If you take a step back, even in normal accounting / banking practices, or MS Excel,
using parens for negative numbers is an common and an industry practice.