2

Is it possible in Powershell to generate functions based on a set of input variables? I've tried wrapping the conditions in script blocks and brackets to force evaluation, but at best I get this as the return:

The term 'function' is not recognized as the name of a cmdlet, function, [...]

Otherwise the function appears to run, but the new function binding does not get created.

This does not work (nor does wrapping the body in & {}, & ({}), & {()})

function gen-test ($test) {
    function get-$test {
        Write-Output "This is $test"
    }
}

I want the names to be generated based on the passed value, not predefined.

Context

I have to support multiple domains and am looking for a way to simplify the coding of functions to return specific information from them. Currently I have sets of functions of the type Get-<domain>Info (one for each domain) where info depends on whether I want account settings, group membership, etc.

If there is no way to get this done, I will just have to fall back to Get-Info <identification> -server <domain> with a default domain to query. However I intend to share these with my colleagues and I want to make it as simple/straightforward as possible.

1 Answer 1

5

You can create a function using New-Item and the PSDrive Function:

Example:

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))
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.