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 ?
You have a chicken-and-egg problem:
Get-Module posh-gitonly returns a valid module info object once posh-git has already been importedImport-Module posh-gitonce that happensAdd the
-ListAvailableswitch parameter to theGet-Modulecall to discover modules that are available for import:As zett42 suggests you could even get rid of the
Get-Modulecall altogether: just attempt to import the module and see if it succeeds: