Reputation: 19
I know I can limit exported commands from module that is imported like this:
Import-Module C:\...\MyModule
or Import-Module C:\...\MyModule\MyModule.psd1
Then I can use CmdletsToExport in .psd1.
But, what if I import module from .dll?
Import-Module C:\...\MyModule.dll
How to limit exported commands (cmdlets)?
There are cmdlets in our .dll that should be "hidden" in default and we want to allow calls of them only if some environment variable has some value.
I was thinking that Powershell maybe uses reflection to get commands from .dll, so maybe there is some way to catch some "module initialized" event where I could somehow influence what cmdlets should be exported.
Upvotes: 1
Views: 76
Reputation: 437042
I can't think of an environment variable-based solution, but if executing a command to make the "hidden" cmdlets visible is acceptable, you can take the following approach:
Create a full-fledged, directory-based module around your cmdlet-containing *.dll
, through whose module manifest (.psd1
) you can limit what cmdlets are made available to the caller on import.
If you want to (later or alternatively) load all cmdlets, run Import-Module -Force
directly on the *.dll
, which will import all cmdlets (all public Cmdlet
and/or PSCmdlet
-derived classes).
If you define helper function Import-AllCmdlets
(source code below), you can force importing of all cmdlets as follows, assuming your module's name is Foo
:
# -Verbose shows what cmdlets are imported.
Get-Module -ListAvailable Foo | Import-AllCmdlets -Verbose
Import-AllCmdlets
source code:function Import-AllCmdlets {
param(
[Parameter(ValueFromPipeline)]
[psmoduleinfo] $module
)
process {
if ($module.RootModule -notlike '*.dll') {
Write-Error "Module $module has no binary root module."
return
}
Import-Module -Force (Join-Path (Split-Path $module.Path) $module.RootModule)
}
}
Upvotes: 0