如何在Powershell中编写函数以创建函数

Jon*_*pin 2 powershell function

在Powershell中是否可以根据一组输入变量生成函数?我尝试将条件包装在脚本块和方括号中以强制进行评估,但充其量我将其作为回报:

The term 'function' is not recognized as the name of a cmdlet, function, [...]
Run Code Online (Sandbox Code Playgroud)

否则,该函数似乎可以运行,但是不会创建新的函数绑定。

这不起作用(也不包裹身体& {}& ({})& {()}

function gen-test ($test) {
    function get-$test {
        Write-Output "This is $test"
    }
}
Run Code Online (Sandbox Code Playgroud)

我希望基于传递的值而不是预定义的名称来生成名称。

语境

我必须支持多个域,并且正在寻找一种简化函数编码以从中返回特定信息的方法。目前,我有一组类型的功能Get-<domain>Info(每个域一个),其中的信息取决于我是否需要帐户设置,组成员身份等。

如果没有办法做到这一点,我将不得不Get-Info <identification> -server <domain>使用默认域进行查询。但是,我打算与同事分享这些内容,并希望使其尽可能简单/直接。

小智 5

您可以使用New-Item和PSDrive Function创建函数:

例:

Function New-Func{
    Param(
        $Prefix
    )
    $Code = @"
        # Your code here
        Write-Output "This is $Prefix"
"@
    $Name = "Global:Get-${Prefix}Info"
    New-Item -Path Function:\ -Name $Name -Value ([ScriptBlock]::Create($Code))
}
Run Code Online (Sandbox Code Playgroud)