Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading