2

So the problem is, that when I run my basic script that simply mirrors whats is passed in on the command line, the arguments aren't separated in the way I would expect them to be.

the basic code is:

write-host "`$args`[0`] = $args[0]"
write-host "`$args`[1`] = $args[1]"
write-host "`$args`[2`] = $args[2]"

and if i call the script as

./script apples oranges bananas

I get

$args[0] = apples oranges bananas[0]
$args[1] = apples oranges bananas[1]
$args[2] = apples oranges bananas[2]

If its important, I'm doing this in powershell 2.0

3 Answers 3

3

You need to wrap the variable into $(..) like this:

write-host "`$args`[0`] = $($args[0])"
write-host "`$args`[1`] = $($args[1])"
write-host "`$args`[2`] = $($args[2])"

This applies for any expression that is not simple scalar variable:

$date = get-date
write-host "day: $($date.day)"
write-host "so web page length: $($a = new-object Net.WebClient; $a.DownloadString('http://stackoverflow.com').Length)"
write-host "$(if (1 -eq (2-1)) { 'is one' } else {'is not'} )"
Sign up to request clarification or add additional context in comments.

Comments

2

Here's a helper function I use in my profile:

function Echo-Args
{
    for($i=0;$i -lt $args.length;$i++)
    {
        "Arg $i is <$($args[$i])>"
    }
}

PS > Echo-Args apples oranges bananas
Arg 0 is <apples>
Arg 1 is <oranges>
Arg 2 is <bananas>

1 Comment

Nice. To use this to show a script's or function's arguments, place Echo-Args $args inside.
0

Wow, so um, embarrassing.

If you wrap $args[0], for example, in double quotes, like I did above, it will interpret $args and stop, never getting to the [], and therefore printing off the $arg, or the entire array of command line arguments.

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.