So the problem is, that when I run my basic script t开发者_如何学Chat 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
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'} )"
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>
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.
精彩评论