How to export/import cmdlet from local module?

48 Views Asked by At

The problem I have is that cmdlets are not exported and not imported.

Consider following module example (.\Modules\Tools.psm1)

Function Write-Message() {
    param ([String] $Message)
    Write-Information -InformationAction Continue $Message
}

function Write-Debug() {
    [CmdletBinding()]
    param ([String] $Message)
    Write-Verbose $Message
}

Export-ModuleMember `
    -Function Write-Message `
    -Cmdlet Write-Debug

The intended usage (.\Main.ps1):

[CmdletBinding()]
param()

Import-Module $PSScriptRoot\Modules\Tools.psm1

Write-Debug "is just a test"
Write-Message "hello world!"

The execution:

pwsh -file .\main.ps1 -Verbose
VERBOSE: Loading module from path 'C:\dev\snippets\powershell\modules\Modules\Tools.psm1'.
VERBOSE: Exporting function 'Write-Message'.
VERBOSE: Importing function 'Write-Message'.
hello world!

I would like to see:

  • The export and import of Write-Debug (as cmdlet) -> as function wouldn't allow to pass the common parameters
  • And the VERBOSE output "is just a test"

What did I wrong?

1

There are 1 best solutions below

0
Thomas Lehmann On BEST ANSWER

I believe I found the answer of the problem:

-Cmdlet

Specifies the cmdlets that are exported from the script module file. Enter the cmdlet names. Wildcard characters are permitted.

You cannot create cmdlets in a script module file, but you can import cmdlets from a binary module into a script module and re-export them from the script module.

(extract from Export-ModuleMember)

And the answer to my problem:

. $PSScriptRoot\Modules\Tools.ps1

Instead of import-Module I can source the script and all works as required (-Confirm, -WhatIf, -Verbose, ...). I was forced to use .ps1 instead of .psm1 because on each sourcing an editor was opened up with the file.