使用 pester 测试 powershell DSC 脚本 class - 无法找到类型 [ClassName]

Testing a powershell DSC script class with pester - Unable to find type [ClassName]

我正在尝试在 pester 的帮助下测试一些编写为 class 的自定义 DSC 资源。但是,我正在努力研究如何使 class 可用于不同的文件。这真的不是麻烦问题,我也不能在 powershell 中执行此操作。我有一个带有 class 的模块,与 SxDeployment.psm1 文件

中的以下内容非常相似
[DscResource()]
class SxWindowsService {
    [void]Set(){
    }
    [bool]Test(){
        return $true;
    }
    [SxWindowsService]Get(){
        return $this
    }
}

此模块有一个对应的 .psd1,它将 SxWindowsService class 列为 'DscResourcesToExport'。它被注册为一个模块,我可以在执行 Get-Module -ListAvailable 时看到这个模块,也可以对其执行 Import-Module。

我想我的问题确实是如何从另一个文件创建对此 class 的引用?

假设我有一个不同的文件测试。ps1 具有以下内容

Import-Module SxDeployment

$class = [SxWindowsService]::new()

我收到以下错误,"Unable to find type [SxWindowsService]."

更新 经过一些修改后,我可以通过将 .psm1 文件更改为 .ps 文件并更改 .import-module 语句来创建 class 的实例。 .\SxDeployment.ps1。所以看起来问题是如何使用 DSC 配置之外的 DSC 资源模块文件中定义的资源?

类型文字 [SxWindowsService] 将无法在模块外访问。这是设计使然。这是发行说明中的​​引述:

Class keyword >>> Defines a new class. This is a true .NET Framework type. Class members are public, but only public within the module scope. You can't refer to the type name as a string (for example, New-Object doesn't work), and in this release, you can't use a type literal (for example, [MyClass]) outside the script/module file in which the class is defined.

编辑:

好了上面说了这么多。由于 .NET 和 PowerShell 中的对象激活之间存在一些不匹配,因此我心想,可能只是一种方法。我找到了:

Import-Module C:\ps\Whosebug743812\issue.psm1 -Force
function New-PSClassInstance {
    param(
        [Parameter(Mandatory)]
        [String]$TypeName,
        [object[]]$ArgumentList = $null
    )
    $ts = [System.AppDomain]::CurrentDomain.GetAssemblies() |
        Where-Object Location -eq $null | 
            Foreach-Object {
                $_.Gettypes()
            } | Where-Object name -eq $TypeName |
                Select-Object -Last 1
    if($ts) {
        [System.Activator]::CreateInstance($ts,$ArgumentList )
    } else {
        $typeException = New-Object TypeLoadException $TypeName        
        $typeException.Data.Add("ArgumentList",$ArgumentList)
        throw $typeException
    }
}
New-PSClassinstance -TypeName SxWindowsService