首页 > 解决方案 > 在powershell cmdlet中调用函数作为参数

问题描述

function test([string]$word){
return $word
}

Get-ADUser -Identity Function:\test("bill")

据我所知,上述内容应该有效。MS在下面有一个示例,看起来他们将函数作为参数调用。但它不适合我。

微软的例子。

Get-ChildItem -Path Function:\Get-*Version | 除去项目

链接 - https://docs.microsoft.com/en-us/powershell/scripting/learn/ps101/09-functions?view=powershell-7.1

标签: powershell

解决方案


要将命令的 / 表达式的输出作为命令参数传递,请使用(...)分组运算符

Get-ADUser -Identity (test "bill")

至于Function:\test语法:只能用于检索函数定义,不能用于直接调用

该语法依赖于Function:PowerShell 驱动器,它提供对所有函数定义的访问 - 请参阅about_Providers概念帮助主题。

为了完整起见(这里没有充分的理由采用这种方法):使用命名空间变量表示法调用运算符&,您可以利用路径语法 - 尽管没有- 如下:Function:\test\

# Same as above.
Get-ADUser -Identity  (& $Function:test "bill")

推荐阅读