Powershell 中的命令行参数

发布于 2024-09-12 13:38:39 字数 472 浏览 7 评论 0原文

所以问题是,当我运行简单地反映命令行上传入的内容的基本脚本时,参数并没有按照我期望的方式分隔。

基本代码是:

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

方式调用脚本

./script apples oranges bananas

如果我按照我得到的

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

如果它很重要,我会在 powershell 2.0 中执行此操作

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

り繁华旳梦境 2024-09-19 13:38:39

您需要将变量包装到 $(..) 中,如下所示:

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

这适用于不是简单标量变量的任何表达式:

$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'} )"

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'} )"
叹沉浮 2024-09-19 13:38:39

这是我在个人资料中使用的辅助函数:

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>

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>
傲鸠 2024-09-19 13:38:39

哇,嗯,好尴尬。

例如,如果将 $args[0] 用双引号括起来,就像我上面所做的那样,它将解释 $args 并停止,永远不会到达 [],因此打印 $arg 或整个命令数组行参数。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文