访问powershell中的$ args数组

时间:2021-09-20 21:25:04

I have a test powershell V2 script that looks like this:

我有一个测试PowerShell V2脚本,如下所示:

    function test_args()
    {
      Write-Host "here's arg 0: $args[0]"
      Write-Host "here's arg 1: $args[1]"
    }


    test_args

If I call this from the powershell command prompt I get this on the screen:

如果我从powershell命令提示符调用它,我会在屏幕上显示:

here's arg[0]: [0]

here's arg[1]: [1]

Not quite what I wanted. It seems I have to copy $args[0] and $args[1] to new variables in the script before I can use them? If I do that I can access things fine.

不是我想要的。在我可以使用之前,似乎我必须将$ args [0]和$ args [1]复制到脚本中的新变量中?如果我这样做,我可以很好地访问。

Is there a way to access the indexed $args in my code? I've tried using curly braces around them in various ways but no luck.

有没有办法在我的代码中访问索引的$ args?我尝试过以各种方式使用花括号,但没有运气。

I'll be moving to named parameters eventually, but the script I'm working on (not this demo one) is a straight port of a batch file.

我最终将转向命名参数,但我正在处理的脚本(不是这个演示版)是批处理文件的直接端口。

1 个解决方案

#1


34  

Try this instead:

试试这个:

function test_args()
{
  Write-Host "here's arg 0: $($args[0])"
  Write-Host "here's arg 1: $($args[1])"
}

test_args foo bar

Note that it is $args and not $arg. Also when you use a PowerShell variable in a string, PowerShell only substitutes the variable's value. You can't directly use an expression like $args[0]. However, you can put the expression within a $() sub-expression group inside a double-quoted string to get PowerShell to evaluate the expression and then convert the result to a string.

请注意,它是$ args而不是$ arg。此外,当您在字符串中使用PowerShell变量时,PowerShell仅替换变量的值。您不能直接使用$ args [0]之类的表达式。但是,您可以将表达式放在双引号字符串中的$()子表达式组中,以使PowerShell评估表达式,然后将结果转换为字符串。

#1


34  

Try this instead:

试试这个:

function test_args()
{
  Write-Host "here's arg 0: $($args[0])"
  Write-Host "here's arg 1: $($args[1])"
}

test_args foo bar

Note that it is $args and not $arg. Also when you use a PowerShell variable in a string, PowerShell only substitutes the variable's value. You can't directly use an expression like $args[0]. However, you can put the expression within a $() sub-expression group inside a double-quoted string to get PowerShell to evaluate the expression and then convert the result to a string.

请注意,它是$ args而不是$ arg。此外,当您在字符串中使用PowerShell变量时,PowerShell仅替换变量的值。您不能直接使用$ args [0]之类的表达式。但是,您可以将表达式放在双引号字符串中的$()子表达式组中,以使PowerShell评估表达式,然后将结果转换为字符串。