function - 为什么我的参数没有传递给函数?
问题描述
创建函数时,我在家用笔记本电脑上遇到了奇怪的行为。参数不传递给函数。
例子:
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
我也只是想用参数打印一个详细的语句,但我只得到一个空行。
为什么没有将参数传递给函数?
解决方案
@JosefZ 的评论是正确的。$input 基本上是一个保留变量名称,如about_Automatic_Variables中所述。
包含一个枚举器,它枚举传递给函数的所有输入。$input 变量仅可用于函数和脚本块(它们是未命名的函数)。
因此,更改参数名称应该可以按预期工作。但不要忘记更改调用函数的方式,以便它也使用新的参数名称。在这种情况下,您也可以在调用函数时完全跳过参数名称
function Get-Info { param($myinput) $myinput | gm }
Get-Info -myinput 'test'
Get-Info 'test'
推荐阅读
- android - wordpress 中的本机应用程序 + Api 不适用于 android studio 模拟器
- jenkins - 我们如何向用户或团队提供对特定 Jenkins 作业的访问权限?
- node.js - 为什么我的节点模块没有在 react-native 中使用?
- c++ - 如何子类化组合框编译错误
- mainframe - JCL 在一行中合并记录
- java - 如何在java中将字符串时间戳转换为日期?
- terraform - 在 Terraform Enterprise 中可以创建的工作空间的数量是否有限制?
- python - ValueError:'X'不在列表中,为什么我不能使用字符串查找和替换
- jira-xray - 在文档生成器中添加前提条件描述
- javascript - Selectpicker 选择了第一个选项,但 selectpicker 标题是“未选择”