supercheetah
supercheetah

Reputation: 3250

Passing arrays as parameters in Powershell?

I have this function in 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
}

And in some code elsewhere, I call it thusly:

$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

When it's called, $proc_path gets the value for $reg_exe, but $args is blank.

This is how array parameters are passed in Powershell, isn't it?

Upvotes: 4

Views: 4531

Answers (1)

briantist
briantist

Reputation: 47792

$args is a special (automatic) variable in PowerShell, don't use it for your parameter name.

-ArgumentList is the typical name given to this type of parameter in PowerShell and you should stick to the convention. You could give it an alias of args and then you could call it the way you like without conflicting with the variable:

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
}

A possible alternative, that may work if you absolutely must name the parameter as args (untested):

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
}

Please don't do this though; the other workaround is better.

Upvotes: 3

Related Questions