为什么我的参数没有传递到函数中?

Ale*_*x_P 3 powershell function parameter-passing

创建功能时,我的家用笔记本电脑出现异常行为。参数不会传递到函数中。

例:

function Get-Info {
    param (
        $input
    )
    $input | gm
}
Run Code Online (Sandbox Code Playgroud)

使用此代码(Get-Info -input 'test'),我收到以下错误:

gm : You must specify an object for the Get-Member cmdlet.
At line:5 char:14
+     $input | gm
+                   ~~
    + CategoryInfo          : CloseError: (:) [Get-Member], InvalidOperationException
    + FullyQualifiedErrorId : NoObjectInGetMember,Microsoft.PowerShell.Commands.GetMemberCommand
Run Code Online (Sandbox Code Playgroud)

我也只是尝试打印带有参数的详细语句,但我只得到一个空行。

为什么参数没有传递到函数中?

Rya*_*ger 6

@JosefZ的评论是正确的。$ input基本上是保留的变量名称,如about_Automatic_Variables中所述

包含一个枚举器,该枚举器枚举传递给函数的所有输入。$ input变量仅对函数和脚本块(未命名的函数)可用。

因此,更改参数名称应该可以按预期工作。但是不要忘记也要更改函数的调用方式,以便它也使用新的参数名称。在这种情况下,您也可以在调用函数时完全跳过参数名称

function Get-Info { param($myinput) $myinput | gm }
Get-Info -myinput 'test'
Get-Info 'test'
Run Code Online (Sandbox Code Playgroud)