一个New-Module可以返回一个psobject吗?

时间:2016-06-22 23:24:46

标签: powershell powershell-module

下面的这个模块返回一个空对象。有什么建议可以解决吗?

New-Module -ScriptBlock { 
    $resourcesDirectory="AA"
    .....
    $commonProperties = New-Object PSObject -Property @{
        ResourcesDirectory = $resourcesDirectory
    }

    return $commonProperties 
} -name GetXXX

1 个答案:

答案 0 :(得分:1)

PetSerAl寻求帮助的提示。

New-Module默认返回新创建的模块,作为[System.Management.Automation.PSModuleInfo]实例。

通过“返回一个空对象”我认为你的意思是你的意图是让你的模块导出 $commonProperties 变量 (恰好包含[pscustomobject]个实例,但这是偶然的,但您的代码却没有这样做。

原因是缺少Export-ModuleMember次调用,变量别名 - 与函数不同 - 是自动从模块导出

警告

  • 如果一个或多个Export-ModuleMember来电 导出指定的成员(不会自动导出任何内容)。

  • Export-ModuleMember次调用最佳位置位于模块定义的底部,因为它们必须在之后要自行导出的元素的定义。

  • 如果要将导入当前会话的导出成员集限制为模块函数子集,则可以使用{{ 1}} New-Module参数。

    • 如果仅在当前会话中使用该模块,则-FunctionNew-Module -Function合并是没有意义的。另请注意,使用Export-ModuleMember将阻止非功能成员导入当前会话。
    • 结合默认导出行为,-Function 有效地提供了使用带有脚本块内部函数名称的显式New-Module -Function调用的替代方法,尽管理解它很重要这两种机制不同。

要导出变量Export-ModuleMember,您需要调用$commonProperties (请注意变量名称中缺少前缀Export-ModuleMember -Variable commonProperties):

$

鉴于$newModule = New-Module -ScriptBlock { $resourcesDirectory="AA" $commonProperties = New-Object PSObject -Property @{ ResourcesDirectory = $resourcesDirectory } # You must explicitly export variable $commonProperties. # Note that `Export-ModuleMember` must generally come *after* the # definition of the variable, and that the variable name # must not be $-prefixed. Export-ModuleMember -Variable commonProperties # (No need to `return` anything from the script block. # Any output will be ignored.) } -name GetXXX 不仅创建了一个新模块而且自动导入它,New-Module现在在当前会话中可用。

旁注

通过添加开关 $commonProperties ,您可以告诉-ReturnResult 返回脚本块的输出 ,而不是新创建的模块对象(但模块仍然导入到当前会话中)。

由于New-Module语句,应用于将返回变量$commonProperties的代码,但如上所述,您的脚本块不会导出任何成员,因此当前会话将看不到return $commonProperties 变量

或者,切换 $commonProperties 告诉-AsCustomObject 返回其成员为导出成员的New-Module实例
请注意,正常导出规则适用,并且模块仍然在幕后创建,尽管它不是导入

应用于您的(更正的)代码,添加了导出的函数[pscustomobject]

Foo

$newObj = New-Module -ScriptBlock { $resourcesDirectory="AA" $commonProperties = New-Object PSObject -Property @{ ResourcesDirectory = $resourcesDirectory } function Foo { "I'm here." } Export-ModuleMember -Variable commonProperties -Function Foo } -AsCustomObject 现在包含一个名为$newObj的属性,该属性引用新(隐藏)模块的脚本块中的commonProperties变量。

注意:$commonProperty误导性地将此属性的类型报告为Get-Member,建议使用静态值,而导出的函数可能会改变基础变量的值(尽管这会让我感到震惊)异国情调)。真实类型为NoteProperty[System.Management.Automation.PSVariableProperty]显示,而真$newObj.psobject.properties['commonProperties'].GetType().FullName成员的类型为NoteProperty。 功能

同样,导出的函数 [System.Management.Automation.PSNoteProperty]表面为Foo - 类型成员(方法),它在新(隐藏)模块的上下文中运行并看到它的变量。
(暂且不说:ScriptMethod可用于访问隐藏模块。)

相比之下,导出的别名似乎被忽略

警告:不要使用相同的名称导出不同类型的成员(例如,不要定义同名的函数和变量),因为只有其中一个可以访问。