Home > Enterprise >  Is it possible to call an function nested in another function (PowerShell)?
Is it possible to call an function nested in another function (PowerShell)?

Time:05-18

I'm very used to Python where functions can be put in classes and called separately.

However, now I have to code something in PowerShell and I can't find a way if something similar would be possible here.

An example of what I'm trying to do:

function a {
    Write-Host "a"

    function a_1() { Write-Host "a_1" }

    function a_2() { Write-Host "a_2" }
    
}

a      # Works
a.a_1  # Doesn't works
a_2    # Doesn't works

CodePudding user response:

PowerShell (5 and above) does have support for classes, (see about_Classes) and class methods can be static.

So for example:

class a {
    a() {
        Write-Host "a"
    }
    static [void]a_1()
    {
        Write-Host "a_1"
    }
    static [void]a_2()
    {
        Write-Host "a_2"
    }
}

[a]$a = [a]::new()
[a]::a_1()
[a]::a_2()

Output:

a
a_1
a_2

CodePudding user response:

Only if the inner function have a scope modifier, i.e.: function script:a_1() { ... } or function global:a_2() { ... } – Santiago Squarzon

Thanks! This seems close enough to what I'm searching for, in combination with creative naming of the functions this makes it possible to get something I'm used to.

Solution for me:

function a {
    Write-Host "a"

    function script:a.a_1() { Write-Host "a_1" }

    function script:a.a_2() { Write-Host "a_2" }
    
}

a       # Call this so the functions get loaded
a.a_1   # Creative naming so it acts like I need it
a.a_2
  • Related