Home > other >  Use value of parameter in inner (global) function
Use value of parameter in inner (global) function

Time:11-28

In PowerShell, I'm trying to customise the prompt inside a function that creates a development shell. I do that by creating an inner function prompt, with global scropt.

function Enter-DevEnvironment {
    Param(
        [Parameter()] [ValidateSet('Debug', 'Release')] $flavor = 'Debug'
    )

    function global:prompt {
        "[$flavor] $($executionContext.SessionState.Path.CurrentLocation)>"
    }
}

The problem is that while the function Enter-DevEnvironment has a variable $flavor, this variable is not available for the prompt function.

I've workedaround this by creating a yet another global variable ($global:DevFlavor = $flavor), and using DevFlavor inside prompt, but it left me wonder, whether a cleaner solution is available. I.E. creating an inner function using values from the outer scope by value, and not refering to a variable that may or may not be defined.

CodePudding user response:

This can be done without creating a global variable, by defining the prompt function using New-Item. This allows us to pass a ScriptBlock and use its method GetNewClosure() to bake the value of the -flavor parameter into the function.

function Enter-DevEnvironment {
    Param(
        [Parameter()] [ValidateSet('Debug', 'Release')] $flavor = 'Debug'
    )
         
    $null = New-Item Function:\global:prompt -Force -Value {        
        "[$flavor] $($executionContext.SessionState.Path.CurrentLocation)>"
    }.GetNewClosure()
}
  • Related