powershellpowershell-7.2

Create a function in the global scope in an if block


I'm writing a PS profile that I'm hoping to use across multiple computers.

In this profile, I'm including a few utility functions.

However, I know that sometimes, a module that I one of those functions depdnds on will ont be available, and so I'd like to not create it.

An example of such a function:

if(Get-Module -Name Posh-Git -ErrorAction SilentlyContinue)
{
    Import-Module posh-git

    function global:Push-GitBranch() 
    {
        git push --set-upstream origin (Get-GitStatus).Branch
    }
}

However, when I use this profile, the function is not available. It however is when I define it outside of the if block.

Is it at all possible ? Or should I just add a condition in my function to display a message if a dependency was not found ?


Solution

  • You have a chicken-and-egg problem:

    Add the -ListAvailable switch parameter to the Get-Module call to discover modules that are available for import:

    if(Get-Module -Name Posh-Git -ListAvailable -ErrorAction SilentlyContinue)
    {
        Import-Module posh-git
    
        function global:Push-GitBranch() 
        {
            git push --set-upstream origin (Get-GitStatus).Branch
        }
    }
    

    As zett42 suggests you could even get rid of the Get-Module call altogether: just attempt to import the module and see if it succeeds:

    if(Import-Module posh-git -PassThru -ErrorAction SilentlyContinue)
    {
        # posh-git is definitely imported by now
        function global:Push-GitBranch() 
        {
            git push --set-upstream origin (Get-GitStatus).Branch
        }
    }