2

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
}
2
  • 2
    $args -> ${Something else that do not clash with $args automatic variable} Commented Nov 27, 2016 at 14:12
  • You also should move your function definition above your function call to improve script readability. Commented Nov 27, 2016 at 16:04

1 Answer 1

4

$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. 
Sign up to request clarification or add additional context in comments.

1 Comment

Nicely done. Unfortunately, "prevented from using" with respect to $args means: "you're free to declare a parameter by this name, but it will be ignored", which is arguably a bug. By contrast, trying to name a parameter $PSHOME, for instance, more sensibly results in error Cannot overwrite variable PSHOME because it is read-only or constant.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.