Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

accessing the $args array in powershell

I have a test powershell V2 script that looks like this:

    function test_args()     {       Write-Host "here's arg 0: $args[0]"       Write-Host "here's arg 1: $args[1]"     }       test_args 

If I call this from the powershell command prompt I get this on the screen:

here's arg[0]: [0]  here's arg[1]: [1] 

Not quite what I wanted. It seems I have to copy $args[0] and $args[1] to new variables in the script before I can use them? If I do that I can access things fine.

Is there a way to access the indexed $args in my code? I've tried using curly braces around them in various ways but no luck.

I'll be moving to named parameters eventually, but the script I'm working on (not this demo one) is a straight port of a batch file.

like image 262
larryq Avatar asked Sep 07 '12 22:09

larryq


People also ask

How do you access an array in PowerShell?

To access items in a multidimensional array, separate the indexes using a comma ( , ) within a single set of brackets ( [] ). The output shows that $c is a 1-dimensional array containing the items from $a and $b in row-major order.

What is $args in PowerShell?

$args. Contains an array of values for undeclared parameters that are passed to a function, script, or script block. When you create a function, you can declare the parameters by using the param keyword or by adding a comma-separated list of parameters in parentheses after the function name.

What is the $_ variable in PowerShell?

The “$_” is said to be the pipeline variable in PowerShell. The “$_” variable is an alias to PowerShell's automatic variable named “$PSItem“. It has multiple use cases such as filtering an item or referring to any specific object.

How do I get the first element of an array in PowerShell?

Windows PowerShell arrays are zero-based, so to refer to the first element of the array $var3 (“element zero”), you would write $var3 [0].


1 Answers

Try this instead:

function test_args() {   Write-Host "here's arg 0: $($args[0])"   Write-Host "here's arg 1: $($args[1])" }  test_args foo bar 

Note that it is $args and not $arg. Also when you use a PowerShell variable in a string, PowerShell only substitutes the variable's value. You can't directly use an expression like $args[0]. However, you can put the expression within a $() sub-expression group inside a double-quoted string to get PowerShell to evaluate the expression and then convert the result to a string.

like image 178
Keith Hill Avatar answered Sep 20 '22 13:09

Keith Hill