如何公开从所需模块导入的类型?

时间:2019-01-11 17:54:19

标签: powershell

在以下涉及2个模块的场景中,如何公开test类型,以便Get-Result中的MainModule.psm1可以使用它?

我当前的结果是Unable to find type [Test]

场景

MainModule在其RequiredModules PSD1中具有ReferenceModule

MainModule具有一个名为Get-Result的函数,该函数将test类作为参数。

ReferenceModule包含test类的定义。

完整的可复制示例

$MyModulePSD1 = @"
@{
RootModule = 'MyModule.psm1'
ModuleVersion = '0.0.0.1'
GUID = '8428874a-381f-473a-b754-43304df5a219'
RequiredModules = @("$($Env:USERPROFILE)\desktop\MyModule\ReferenceModule.psd1")
FunctionsToExport  = '*'
}
"@

$ReferenceModulePSD1= @"
@{
RootModule = 'ReferenceModule.psm1'
ModuleVersion = '0.0.0.1'
GUID = '8428874a-381f-473a-b754-22222225a219'
FunctionsToExport  = '*'
}
"@


$MyModulePSM1 = @'
    Function Get-Result([Test]$MyParam) {
        return $true
    }
'@


$ReferenceModulePSM1 = @'
class test {
    [String]$test
}
'@

New-Item -Path "$($Env:USERPROFILE)\desktop\MyModule" -ItemType Directory -Force
New-Item -Path "$($Env:USERPROFILE)\desktop\ReferenceModule" -ItemType Directory -Force

Set-Content -Path "$($Env:USERPROFILE)\desktop\MyModule\MyModule.psd1" -Value $MyModulePSD1
Set-Content -Path "$($Env:USERPROFILE)\desktop\MyModule\MyModule.psm1" -Value $MyModulePSM1

Set-Content -Path "$($Env:USERPROFILE)\desktop\MyModule\ReferenceModule.psm1" -Value $ReferenceModulePSM1
Set-Content -Path "$($Env:USERPROFILE)\desktop\MyModule\ReferenceModule.psd1" -Value $ReferenceModulePSD1


Import-Module "$($Env:USERPROFILE)\desktop\MyModule\MyModule.psd1" -Force

Get-Result

1 个答案:

答案 0 :(得分:1)

您应该使用“ using”关键字来引用参考模块。请注意/编辑我的硬编码桌面文件夹。由于某些原因,我无法解释无法在其中使用$Env:USERPROFILE变量。

$MyModulePSD1 = @"
@{
RootModule = 'MyModule.psm1'
ModuleVersion = '0.0.0.1'
GUID = '8428874a-381f-473a-b754-43304df5a219'
RequiredModules = @("$($Env:USERPROFILE)\desktop\MyModule\ReferenceModule.psd1")
FunctionsToExport  = '*'
}
"@

$ReferenceModulePSD1= @"
@{
RootModule = 'ReferenceModule.psm1'
ModuleVersion = '0.0.0.1'
GUID = '8428874a-381f-473a-b754-22222225a219'
FunctionsToExport  = '*'
}
"@


$MyModulePSM1 = @'
    using module 'C:\Users\gertjan\Desktop\MyModule\ReferenceModule.psm1'
    Function Get-Result([Test]$MyParam) {
    return $true
}
'@


$ReferenceModulePSM1 = @'
class test {
    [String]$test
}
'@

New-Item -Path "$($Env:USERPROFILE)\desktop\MyModule" -ItemType Directory -Force
New-Item -Path "$($Env:USERPROFILE)\desktop\ReferenceModule" -ItemType Directory -    Force

Set-Content -Path "$($Env:USERPROFILE)\desktop\MyModule\MyModule.psd1" -Value $MyModulePSD1
Set-Content -Path "$($Env:USERPROFILE)\desktop\MyModule\MyModule.psm1" -Value $MyModulePSM1

Set-Content -Path "$($Env:USERPROFILE)\desktop\MyModule\ReferenceModule.psm1" -Value $ReferenceModulePSM1
Set-Content -Path "$($Env:USERPROFILE)\desktop\MyModule\ReferenceModule.psd1" -Value $ReferenceModulePSD1


Import-Module "$($Env:USERPROFILE)\desktop\MyModule\MyModule.psd1" -Force

Get-Result