Jun Pang
Jun Pang

Reputation: 91

How do I import a Powershell cmdlet globally from a function in another module?

I'm hitting a problem importing cmdlet globally from a function in another module.

Here is the case. Say I'm trying to call Test-Method in an dll. When I run Import-Module <dll path>, things work normally and I can call the Test-Method with no problem.

Then I put the command into a function to simplify usage. Now I have something like:

function Import-Cmdlets
{
    Import-Module "<dll path>" -Scope Global -Force
}

Now in Powershell I call Import-Cmdlets, and then I can call Test-Method with no problem.

However, when I put the function into a psm1 file, and import module on the psm1 file, I cannot find Test-Method anymore.

Now I have a mymodule.psm1 file with following content:

function Import-Cmdlets
{
    Import-Module "<dll path>" -Scope Global -Force
}

Then in PowerShell I run:

Import-Module mymodule.psm1 -Force
Import-Cmdlets

Now I cannot find Test-Method any more. The dll shows up when I run Get-Module and I can see Test-Method from ExportedCommands. But I cannot access it.

This only happens for dll imports. I’ve tried to use a psm1 file to replace the dll path, and didn’t meet this issue.

What is a good work around or solution for this problem?

Upvotes: 5

Views: 3123

Answers (3)

Peter Franta
Peter Franta

Reputation: 36

Had the same problem when importing Cmdlet dll.

Use

New-ModuleManifest "...ManifestName.psd1"

Edit the RootModule entry to specify the Cmdlet dll.

Then Import this Manifest File and all Cmdlets will be exported (or a subset if you list them in the manifest)

The alternative I did before learning about manifests was to create a psm1 wrapper module that imported the cmdlet dll and then used export-modulemember... Manifest is cleaner but either way you have to create an additional file

Upvotes: 0

Evgeny Danilenko
Evgeny Danilenko

Reputation: 181

The reason you still don't get the function imported in your other script when doing Import-Module "script.psm1" is because your "Import-Cmdlets" is not exported. to export the functions, or any other module members is done like so:

Export-ModuleMember -Function "Import-Cmdlets"

now your Import-Cmdlets will become available for usage.

Upvotes: 0

Pierre Goch
Pierre Goch

Reputation: 109

I had the same problem and adding the parameter -Scope Global fixed it

Change your line to Import-Module <path to your module> **-Scope Global**

Upvotes: 1

Related Questions