Freigeben über


Passing arguments from the command line to downstream functions in Powershell

$args is a special variable, an array of all arguments passed to a function on the command line. But, $args is always treated as an array in PowerShell. And It may cause an interesting side effect when passing $args to a downstream function.
Suppose we define a function as follows:
function t1
{
“args : $args, $($args.count)”
}
If you call the function in the command line as follows:
PS : Yjhong>C:\t1 r t g
The result will be
args: r t, 2
But, if you call the function in a function as follows:
function t2
{
t1 $args # my intention is passing the command line arguments that t2 received to the nested function, t1.
}
And, if you run the t2 as follows, you will get a different result as follows:
PS : Yjhong>C:\t2 r t
args: System.Object[], 1
It means that when the t1 function is called in a function, t1 will receive one System.Object[] object consisting of two elements, ‘r’, and ‘t’

Comments