4

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?

1 Answer 1

3

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

Sign up to request clarification or add additional context in comments.

3 Comments

Ah, jeez, okay, thank you. I didn't think of it as possibly being an automatic variable.
@supercheetah the way you worded that comment I totally read it in the voice of Jerry Gergich :)
Now you've got that in my head too.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.