导入类PowerShell5模块

时间:2018-03-20 14:14:17

标签: windows powershell

我已经创建了一些类,我想分成几个文件。不幸的是,继承不起作用。我唯一有效的解决方案是:

Using Module "<Path>"

这不灵活,是调整的噩梦。 我的测试文件夹结构如下所示:

Project
|
+-- classes
|   |
|   +-- domain
|   |   |
|   |   +---Domain.psm1
|   |
|   +-- dns
|       |
|       +--DNS.psm1
|
|
+-- functions
    |
    +-- test
        | 
        +-- test.ps1 

这里提到了我目前的方法,包括课程: https://info.sapien.com/index.php/scripting/scripting-classes/import-powershell-classes-from-modules

Domain.psm1:

class Domain
{
[string] fullname () {
    return "test.local";
}

static [Domain] $instance

static [Domain] GetInstance() {

    if ($null -eq [Domain]::instance) {

        [Domain]::instance = [Domain]::new()
    }

    return [Domain]::instance
}
}

DNS.psm1:

# Working:
#using module "C:\Users\test\Desktop\Project\classes\domain\Domain.psm1"

# Not working:
$scriptDir = Join-Path -Path $PSScriptRoot -ChildPath ..\.. -Resolve
$classFile = -join($scriptDir, "\classes\domain\Domain.psm1")

$scriptBody = "using module $classFile"
$script = [ScriptBlock]::Create($scriptBody)
. $script

class DNS : Domain
{

    [int] testRecord() {

        return 9000;
    }

    # Init Singleton
    static [DNS] $instance

    static [DNS] GetInstance() {

        if ($null -eq [DNS]::instance)
        {
            [DNS]::instance = [DNS]::new()
        }

        return [DNS]::instance
    }
}

test.ps1:

$scriptDir = Join-Path -Path $PSScriptRoot -ChildPath ..\.. -Resolve
$classFile = -join($scriptDir, "\classes\dns\DNS.psm1")

# Working: 
# Include DNS.psm1
$scriptBody = "using module $classFile"
$script = [ScriptBlock]::Create($scriptBody)
. $script

$task = [DNS]::GetInstance()
$task.testRecord()
$task.fullname()

在我的test.ps1中,我创建了一个扩展Domain类的DNS类实例。扩展域失败:

+     . $script
+     ~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (C:\Users\test...\dns\DNS.psm1:String) [], RuntimeException
    + FullyQualifiedErrorId : TypeNotFound

有没有一种简单的方法可以让它发挥作用?

0 个答案:

没有答案