将 $args 变量传递给函数

Passing in $args variable to function

我有一个脚本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:

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

不过,请注意,如果要按名称传递参数,则需要使用展开运算符 @ 调用 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

基于 Jeroen Mostert 的评论*;解决方案如下。 基本上我错误地尝试 'overload' 或 'shadow' 内置 $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