1

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
3
  • Only if the inner function have a scope modifier, i.e.: function script:a_1() { ... } or function global:a_2() { ... } Commented May 17, 2022 at 13:15
  • You may be looking for PowerShell modules; they don't let you nest functions this way, but they do allow grouping functions together Commented May 17, 2022 at 13:18
  • 2
    This is a scoping issue - the functions a_1 and a_2 are defined in the scope of a, and thus cease to exist once the function returns. You can persist them in the calling scope by using the . dot-source invocation operator: . a; a_1; a_2 Commented May 17, 2022 at 13:20

2 Answers 2

5

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

Comments

1

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

1 Comment

Actually what Mathias suggested is much more elegant than modifying the inner function's scope.

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.