How do I import specific functions from a module explicitly?

Viewed 43

This is for readability and safety (clobbering duplication functions) and finding a workaround for no namespace support with PowerShell modules.

I want to be able to do something like this:

Import-Module MyHelpers.psm1 -Functions "FuncOne" -as MyHelpers.Func-One

MyHelpers.Func-One -blah sfsdfsdf

This make it obvious where FuncOne lives. for larger scripts I consider this pretty serious requirement.

It would probably be good enough if I could at least explicitly define which functions I'm importing (without being able to rename them). At least I would see where they are coming from. Is there any support for this? If not then I'll just have to name all functions inside of MyHelpers like MyHelpers.Func-One but then PowerShell will complain the verb is wrong; would that also break other things too?

2 Answers

Here's my comment as answer:

You can use the Function parameter to restrict the function (s) you want to import.

Next, with the Prefix parameter you can add a prefix string to these imported functions.

See Import- module examples 5 and 6

Theo's answer is correct, just want to point out also that you can fully qualify commands that you call by prefixing them with the module name already, for example:

Microsoft.PowerShell.Core\Import-Module -Name ActiveDirectory

ActiveDirectory\Get-ADComputer $env:COMPUTERNAME

or to your example:

Import-Module MyHelpers.psm1 -Functions "FuncOne" -as MyHelpers.Func-One

MyHelpers\Func-One -blah sfsdfsdf
Related