Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PowerShell - Call a function created in another function

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?

like image 461
Dstr0 Avatar asked Apr 29 '26 09:04

Dstr0


1 Answers

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

like image 102
Mathias R. Jessen Avatar answered May 01 '26 22:05

Mathias R. Jessen