D
D
Dmitry Startsev2014-07-24 19:39:10
PowerShell
Dmitry Startsev, 2014-07-24 19:39:10

How to make a function closure in PowerShell similar to JavaScript?

Started learning PowerShell. I'm trying to return a function from a block that closes to another function like this:

$myFunction = Invoke-Command -ScriptBlock {
    function Bar {
        Write-Host World
    }

    function Foo {
        Write-Host Hello
        Bar
    }

    return ${function:Foo}
}

. $myFunction

In response I get:
Hello
foreach : The term 'Bar' is not recognized as the name of a cmdlet, function, script file, or operable program.

I want to get:
Hello
World

At the same time, I do not want to expose the Bar function to the global scope. How to do this in PowerShell?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
F
FlyingBrick, 2014-07-31
@FlyingBrick

I got it like this:

$myFunction = Invoke-Command -ScriptBlock {
    function Bar
    {
        Write-Host("World")
    }

    function Foo
    {
        Write-Host("Hello"); 
        Bar
    }

return Foo

}

$myFunction

Console wrote:
PS C:\Users\%username%> C:\Users\%username%\Desktop\Untitled2.ps1
Hello
World

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question