2

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!

0

2 Answers 2

4

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

Try this:

$numOfArgs = $args.Length
for ($i=3; $i -lt $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]

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

1 Comment

You need a $ in the first line: $args.Length I tried adding it for you but it got overwritten when you improved your answer.
1

The preferred Powershell way is to use a bind parameter, like this;

param(
  [Parameter(Mandatory=$true)][string[]]$Paths
)

# not sure why we're skipping some elements
$Paths | foreach-object { write-host "folder: $_" }

Which you can specify an array or arguments, like this;

.\myScript.ps1 -Paths c:\,c:\Users\,'c:\Program Files\'

This way it will work with -argument TAB completion and will even give you a brief usage using the get-help cmdlet.

get-help .\myscript.ps1
myScript.ps1 [-Paths] <string[]> [<CommonParameters>]

Comments

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.