2011-10-19 48 views
4

想寫師的一個簡單的功能,但我得到一個錯誤(「/」)在功能上

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 

什麼是我的錯?謝謝

+0

[Powershell - 多個函數參數]可能的重複(http://stackoverflow.com/questions/4988226/powershell-multiple-function-parameters) – manojlds

回答

6

您正在調用該功能不正確。函數調用的Powershell語法是:

Div 1 1 

而(1,1)是Object []。

如果你想避免使用錯誤這樣,聲明該函數爲:

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

的[參數(強制性= $真實),確保這兩個值中給出。無論如何,除了Powershell,Division總是會進行雙重除法,即使給出了整數,所以強制類型[double]不會停止整數使用,並且會確保輸入類型符合您的期望。

-1

你應該投除法運算符的參數在整數函數體內,否則 他們將被視爲字符串(即使它們看起來像整數),和字符串不支持/運營商:

[int] $x/[int] $y

+0

'Function Div($ x,$ y){[int ] $ x/[int] $ y}'產生錯誤'無法將類型爲「System.Object []」的「System.Object []」值轉換爲鍵入「System.Int32」'。我相信VoidStar給出了正確的答案。 – Loom