Home > Net >  Create a function in the global scope in an if block
Create a function in the global scope in an if block

Time:09-23

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 ?

CodePudding user response:

You have a chicken-and-egg problem:

  • Get-Module posh-git only returns a valid module info object once posh-git has already been imported
  • You only Import-Module posh-git once that happens

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
    }
}
  • Related