【问题标题】:Calling function as parameter in powershell cmdlet在powershell cmdlet中调用函数作为参数
【发布时间】:2021-01-07 06:24:38
【问题描述】:
function test([string]$word){
return $word
}

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

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

MS 示例。

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

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

【问题讨论】:

  • 您需要将 func 及其参数用括号括起来,以强制 func 在将值传递给调用 func/cmdlet 之前进行评估。
  • 顺便说一句:必须调用 PowerShell 函数、cmdlet、脚本和外部程序类似于 shell 命令 - foo arg1 arg2 - 不像 C#方法 - foo('arg1', 'arg2')。如果您使用, 分隔参数,您将构造一个命令将其视为单个参数数组。为防止意外使用方法语法,请使用Set-StrictMode -Version 2 或更高版本,但请注意其其他影响。请参阅this answer 了解更多信息。

标签: powershell


【解决方案1】:

要将命令的 / 表达式的输出作为命令参数传递,请使用 (...)grouping operator

Get-ADUser -Identity (test "bill")

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

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

为了完整起见(这里没有充分的理由采用这种方法):使用namespace variable notation&call operator,您可以利用Function:\test 路径语法- 尽管没有\ - 如下:

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

【讨论】:

    猜你喜欢
    • 2018-02-17
    • 2011-07-30
    • 1970-01-01
    • 2010-12-05
    • 2011-11-03
    • 1970-01-01
    • 1970-01-01
    • 2020-10-12
    • 1970-01-01
    相关资源
    最近更新 更多