Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing arrays as parameters in Powershell?

Tags:

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?

like image 450
supercheetah Avatar asked Oct 16 '25 14:10

supercheetah


1 Answers

$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.

like image 169
briantist Avatar answered Oct 18 '25 03:10

briantist



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!