在Powershell中将数组作为参数传递?

时间:2016-05-25 18:10:06

标签: powershell

我在PowerShell中有这个功能:

function Run-Process
{
    param([string]$proc_path, [string[]]$args)
    $process = Start-Process -FilePath $proc_path -ArgumentList $args -PassThru -Wait
    $exitcode = Get-ExitCode $process
    return $exitcode
}

在其他地方的某些代码中,我这样称呼它:

$reg_exe = "C:\WINDOWS\system32\reg.exe"
$reg_args = @("load", "hklm\$user", "$users_dir\$user\NTUSER.DAT")
$reg_exitcode = Run-Process -proc_path $reg_exe -args $reg_args

当它被调用时,$proc_path获取$reg_exe的值,但$args为空。

这是在Powershell中传递数组参数的方式,不是吗?

1 个答案:

答案 0 :(得分:3)

$args is a special (automatic) variable in PowerShell,请勿将其用作参数名称。

-ArgumentList是PowerShell中此类参数的典型名称,您应该遵守约定。您可以给它一个别名args,然后您可以按照自己喜欢的方式调用它,而不会与变量冲突:

function Run-Process {
[CmdletBinding()]
param(
    [string]
    $proc_path ,

    [Alias('args')]
    [string[]]
    $ArgumentList
)
    $process = Start-Process -FilePath $proc_path -ArgumentList $ArgumentList -PassThru -Wait
    $exitcode = Get-ExitCode $process
    return $exitcode
}

一种可能的替代方案,如果您绝对必须将参数命名为args(未经测试),则可能会有效:

function Run-Process
{
    param([string]$proc_path, [string[]]$args)
    $process = Start-Process -FilePath $proc_path -ArgumentList $PSBoundParameters['args'] -PassThru -Wait
    $exitcode = Get-ExitCode $process
    return $exitcode
}

请不要这样做;其他解决方法更好。

相关问题