将$ args变量传递给函数

时间:2018-11-09 12:39:44

标签: powershell scripting powershell-v5.0

我有一个脚本tester.ps1;它要做的第一件事是调用一个名为main的函数(在脚本本身内定义)。

我需要传入从命令行传递到 it 的自动变量$args

我该怎么做?

以下内容似乎无效:

#Requires -Version 5.0
#scriptname: tester.ps1
function main($args) {
    Write-Host $args
}
# Entry point
main $args

当我保存此tester.ps1并调用它时,该函数看不到传递的参数吗?

PS> . .\tester.ps1 hello world
From entry point: hello world
From Function:

2 个答案:

答案 0 :(得分:0)

在您的示例中,只需从$args函数声明中删除main,就足以获得所需的输出。

但是,请注意,如果要按名称传递参数,则需要使用格式运算符main调用@,例如:

#Requires -Version 5.0
#scriptname: tester.ps1
function main($myString, $otherVar) {
    Write-Host $myString
}
# Entry point
Write-Host "Not using splatting: " -NoNewline
main $args

Write-Host "Using splatting: " -NoNewline
main @args

输出:

PS> . .\test.ps1 -myString "Hi World" -otherVar foobar
Not using splatting: -myString Hi World -otherVar foobar
Using splatting: Hi World

查找更多关于Splatting运算符@ here

的信息

答案 1 :(得分:0)

基于Jeroen Mostert的评论*;解决方案如下。 基本上,我是错误地尝试“超载”或“阴影化”内置的$ arg变量。 我只需要一个具有不同名称的参数,如下所示:

 #Requires -Version 5.0
    function main($my_args) {
        write-host "From Function:" $my_args 
    }
    # Entry point
    write-host "From entry point:" $args
    main $args

> . .\tester.ps1 hello world
From entry point: hello world
From Function: hello world
相关问题