PowerShell: Import-Module, but no “ExportedCommand

2020-06-04 05:42发布

When I use

Import-Module -Name <path_to_local_dll> -Verbose

the cmdlets contained in the DLL file are not exported.

Thus, when I type Get-Module my imported module is listed, but without any ExportedCommands. Why?

ModuleType Name                      ExportedCommands
---------- ----                      ----------------
Binary     MyModule

On a second PC with the same software (PowerShell, .NET Framework, ...), the same imported DLL file works fine. There I get ExportedCommands.

On what can this behaviour depend?

Unfortunately, the Import-Module cmdlet gives no indication that it failed to import the cmdlets. Is there a way to get an indication why it fails?

5条回答
唯我独甜
2楼-- · 2020-06-04 06:00

It may be that the psd1 file (the module manifest) does not contain the commands.

This page has a tutorial on how to create a module manifest.

查看更多
Ridiculous、
3楼-- · 2020-06-04 06:01

One other requirement: ensure that the cmdlet class is public. For example, in my .cs file I initially had:

[Cmdlet(VerbsCommon.Get, "Proc")]
class GetProcCommand : Cmdlet
{ ...

Even after adding a manifest file with RootModule set, Get-Module continued to show no ExportedCommands after my Import-Module. To fix it I just marked the class as public and rebuilt my .dll assembly:

[Cmdlet(VerbsCommon.Get, "Proc")]
public class GetProcCommand : Cmdlet
{ ...

I figured this out while examining my .dll using ildasm - I noticed that some of my classes were public, but my cmdlet class was private.

查看更多
混吃等死
4楼-- · 2020-06-04 06:09

Two things:

  1. Make sure you're using a module manifest file (.psd1 file). More information can be found in How to Write a Module Manifest

  2. Most importantly, edit your manifest file and make sure it references your root module as follows:

    RootModule = 'name of your module'

I just finished fighting with this for a few hours and I couldn't figure out what I was missing from my other modules. This did the trick for sure!

查看更多
Anthone
5楼-- · 2020-06-04 06:10

Explicitly exporting function from the PowerShell module worked for me:

function New-CmdLetNameHere
{
    ...
}
Export-ModuleMember -Function New-CmdLetNameHere
查看更多
疯言疯语
6楼-- · 2020-06-04 06:22

This is what worked for me:

  1. Run PowerShell with Administrator privileges.

  2. Now run the command Set-ExecutionPolicy Restricted

  3. Now try this:

    Import-Module -Name YourModuleName
    
    Get-Command -Module YourModuleName
    
查看更多
登录 后发表回答