为什么我的Array在发送到函数后是空的

时间:2016-11-27 14:00:56

标签: arrays powershell arguments

我想将多个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
}

1 个答案:

答案 0 :(得分: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.