2016-11-27 42 views
2

我想幾個parameters送入function,其中之一是array。 調用之前function數組是幾個項目,通過在函數內部調試器看時arrayempty\null爲什麼我的數組是空後送入功能

$arr = New-Object System.Collections.ArrayList 
$arr.Add("test1") 
GetProcessOutput -exeFile "c:\file.exe" -args $arr 

function GetProcessOutput($exeFile, $args) 
{ 
    # here my $args is empty -> children could not be evaluated 
} 
+2

'$ args' - >'$ {別的東西,不符合的$ args自動變量}' – PetSerAl

+0

交鋒您還應該將函數定義移到函數調用上方以提高腳本的可讀性。 – user4317867

回答

4

$argsautomatic variable,這意味着你是從使用args名用戶防止定義的變量。

使用任何其他名稱,它會工作:

function GetProcessOutput([string]$exeFile,[array]$arguments) 
{ 
    # $arguments will work just fine 
} 

about_Variables help file

 There are several different types of variables in Windows 
PowerShell. 

-- User-created variables: User-created variables are created and 
    maintained by the user. By default, the variables that you create at 
    the Windows PowerShell command line exist only while the Windows 
    PowerShell window is open, and they are lost when you close the window. 
    To save a variable, add it to your Windows PowerShell profile. You can 
    also create variables in scripts with global, script, or local scope.  

-- Automatic variables: Automatic variables store the state of 
    Windows PowerShell. These variables are created by Windows PowerShell, 
    and Windows PowerShell changes their values as required to maintain 
    their accuracy. Users cannot change the value of these variables. 
    For example, the $PSHome variable stores the path to the Windows 
    PowerShell installation directory. 
+1

很好地完成。不幸的是,對於「「使用防止」 $ args'意思是:「你可以自由通過這個名字來聲明一個參數,但它會被忽略」,這可以說是一個錯誤。 相比之下,試圖命名參數'$ PSHOME',例如,更明智地導致錯誤'不能覆蓋變量PSHOME,因爲它是隻讀或常量。 – mklement0