views:

39

answers:

3

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

A: 

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.

+1  A: 

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'} )"
stej
A: 

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>
Shay Levy