为什么我的数组在发送到函数后为空 [英] Why my Array is empty after sent into function

查看:33
本文介绍了为什么我的数组在发送到函数后为空的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将几个参数发送到function中,其中之一是array.在调用 function 之前,数组有几个项目,当通过函数内部的调试器查看时,arrayempty\null:

$arr = 新对象 System.Collections.ArrayList$arr.Add("test1")GetProcessOutput -exeFile "c:\file.exe" -args $arr函数 GetProcessOutput($exeFile, $args){# 这里我的 $args 是空的 ->无法评估儿童}

解决方案

$args 是一个 自动变量,这意味着您不能将 args 名称用于用户定义的变量.

使用任何其他名称即可:

function GetProcessOutput([string]$exeFile,[array]$arguments){# $arguments 可以正常工作}

<小时>

来自 about_Variables 帮助文件:

<块引用>

 Windows 中有几种不同类型的变量电源外壳.

-- 用户创建的变量:用户创建的变量被创建并由用户维护.默认情况下,您创建的变量Windows PowerShell 命令行仅在 WindowsPowerShell 窗口已打开,关闭窗口时它们将丢失.要保存变量,请将其添加到您的 Windows PowerShell 配置文件中.你可以还可以在具有全局、脚本或局部范围的脚本中创建变量.-- 自动变量:自动变量存储状态Windows PowerShell.这些变量由 Windows PowerShell 创建,和 Windows PowerShell 根据需要更改其值以维护他们的准确性.用户无法更改这些变量的值.例如,$PSHome 变量存储 WindowsPowerShell 安装目录.

I want to send several parameters into function and one of them is array. Before call the function the array is with several items, when looking via the debugger inside the function the array is empty\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
}

解决方案

$args is a automatic variable, meaning that you are prevented from using the args name for a user-defined variable.

Use any other name and it'll work:

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


From the 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. 

这篇关于为什么我的数组在发送到函数后为空的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆