简体   繁体   English

Powershell中的命令行参数

[英]command line arguments in Powershell

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 如果它很重要,我在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. 如果你用$ args [0]换行,例如,用双引号,就像我上面那样,它将解释$ args并停止,永远不会到[],因此打印$ arg或整个命令数组行参数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM