accessing the $args array in powershell

瘦欲@ 提交于 2019-11-29 05:14:27

问题


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

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]

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.

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.


回答1:


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.



来源:https://stackoverflow.com/questions/12326205/accessing-the-args-array-in-powershell

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!