Warm tip: This article is reproduced from serverfault.com, please click

Powershell accessing multiple parameters in a for loop

发布于 2014-11-28 19:08:29

Hi I am very new to powershell and I am writing a script that accepts multiple parameters. These parameters are being accessed in a for loop inside the file. It looks something like this

$numOfArgs = args.Length
for ($i=3; $i -le $numOfArgs; $i++)
{


   write-host "folder: $args[$i]"
   # does something with the arguments

}

However, the output gives me all the parameters as a whole instead of just one parameter specified in the array as an array element? Can someone tell me where is the mistake here? Thanks!

Questioner
user3351901
Viewed
0
Micky Balladelli 2014-11-29 03:19:28

EDIT: Thanks Duncan to point this out, missing a $ in a variable.

Try this:

$numOfArgs = $args.Length
for ($i=3; $i -le $numOfArgs; $i++)
{
   write-host "folder: $($args[$i])"
   # does something with the arguments
}

When placing a variable in a string, the variable is evaluated, not the entire expression. So by surrounding it with $() Powershell will evaluate the whole expression.

In other words, only $args was evaluated instead of $args[$i]