3

When I run this:

function Setup-One{

    function First-Function{
    Write-Host "First function!"
    }

    function Second-Function{
    Write-Host "Second function!"
    }
}
Setup-One

And than I call First-Function or Second-Function, PS says that they don't exist. What am I doing wrong?

1

1 Answer 1

10

Function definitions are scoped, meaning that they stop existing when you leave the scope in which they were defined.

Use the . dot-source operator when invoking Setup, thereby persisting the nested functions in the calling scope:

function Setup-One{

    function First-Function{
    Write-Host "First function!"
    }

    function Second-Function{
    Write-Host "Second function!"
    }
}
. Setup-One

# Now you can resolve First-Function/Second-Function
First-Function
Second-Function

See the about_Scopes help topic for moreinformation on scoping in PowerShell

Sign up to request clarification or add additional context in comments.

4 Comments

Alternatively, function global:First-Function inside Setup-One overrides the scope on a per-declaration basis (what's more convenient varies by how much you intend to expose).
@JeroenMostert feel free to add an answer, but I'm not going to suggest that :-)
@MathiasR.Jessen Thank you very much bro
This right here - Thanks you @MathiasR.Jessen -- This answer is a life saver!

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.