首页 > 解决方案 > 为什么我的参数没有传递给函数?

问题描述

创建函数时,我在家用笔记本电脑上遇到了奇怪的行为。参数不传递给函数。

例子:

function Get-Info {
    param (
        $input
    )
    $input | gm
}

使用此代码(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

我也只是想用参数打印一个详细的语句,但我只得到一个空行。

为什么没有将参数传递给函数?

标签: functionpowershellparameter-passing

解决方案


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

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

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

function Get-Info { param($myinput) $myinput | gm }
Get-Info -myinput 'test'
Get-Info 'test'

推荐阅读