在 powershell 中访问 $args 数组 [英] accessing the $args array in powershell

查看:95
本文介绍了在 powershell 中访问 $args 数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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


    test_args

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

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

here's arg[0]: [0]

here's arg[1]: [1]

不是我想要的.似乎我必须先将 $args[0] 和 $args[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?我尝试过以各种方式在它们周围使用花括号,但没有运气.

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.

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

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.

推荐答案

试试这个:

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

test_args foo bar

请注意,它是 $args 而不是 $arg.此外,当您在字符串中使用 PowerShell 变量时,PowerShell 只会替换该变量的值.您不能直接使用像 $args[0] 这样的表达式.但是,您可以将表达式放在双引号字符串内的 $() 子表达式组中,以使 PowerShell 计算表达式,然后将结果转换为字符串.

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.

这篇关于在 powershell 中访问 $args 数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆