4

I'm trying to write a simple function of the division, but I get an error

PS C:\Users\john> Function Div($x, $y) { $x / $y }
PS C:\Users\john> Div (1, 1)
Method invocation failed because [System.Object[]] doesn't contain a method named 'op_Division'.
At line:1 char:28
+ Function Div($x, $y) { $x / <<<<  $y }
    + CategoryInfo          : InvalidOperation: (op_Division:String) [], RuntimeException
    + FullyQualifiedErrorId : MethodNotFound

What is my mistake? Thanks

Loom
  • 9,768
  • 22
  • 60
  • 112
  • possible duplicate of [Powershell - Multiple Function parameters](http://stackoverflow.com/questions/4988226/powershell-multiple-function-parameters) – manojlds Oct 19 '11 at 21:39

2 Answers2

6

You are invoking the function incorrectly. Powershell syntax for function invocation is:

Div 1 1

Whereas (1,1) is an Object[].

If you want to prevent usage mistakes like this, declare the function as:

Function Div([Parameter(Mandatory=$true)][double]$x, [Parameter(Mandatory=$true)][double]$y) { $x / $y }

the [Parameter(Mandatory=$true)] ensures both values are given. And division always does double division in Powershell anyway, even if integers are given, so enforcing type [double] won't stop integer usage and will make sure the input type is what you expect.

VoidStar
  • 5,241
  • 1
  • 31
  • 45
-1

You should cast the arguments of the division operator to ints in your function body, otherwise they will be treated as strings (even if they look like ints), and strings don't support the / operator:

[int] $x / [int] $y

Kilian Foth
  • 13,904
  • 5
  • 39
  • 57
  • `Function Div($x, $y) { [int] $x / [int] $y }` produces error `Cannot convert the "System.Object[]" value of type "System.Object[]" to type "System.Int32"`. I believe that VoidStar gave correct answer. – Loom Oct 19 '11 at 21:33