点源文件中的 PowerShell 点源 - 导入类

2024-01-12

我的项目结构如下:

MyScript.ps1
classes\
    Car.ps1
    Tesla.ps1

Car.ps1 是 Tesla.ps1 的基类。我尝试在 Tesla.ps1 中这样定义 Tesla:

. "$PSScriptRoot\Car.ps1"

class Tesla : Car
{
}

MyScript.ps1 需要使用 Tesla 类,但不需要知道它继承自 Car。

. "$PSScriptRoot\classes\Tesla.ps1"

$tesla = [Tesla]::new()

点采购至classes\Tesla.ps1工作正常,但 Tesla 文件抛出此错误:

无法找到类型 [汽车]

如果我在 MyScript.ps1 中以正确的顺序导入所有文件,它就可以正常工作。例子:

. "$PSScriptRoot\classes\Car.ps1"
. "$PSScriptRoot\classes\Tesla.ps1"

$tesla = [Tesla]::new()

这很麻烦,尤其是随着复杂性的增加。我的采购点是否错误?是否有更好的方法使用不在 PSModulePath 中的相对路径导入自定义 PowerShell 类?


PetSerAl https://stackoverflow.com/users/4003407/petseral正如之前无数次一样,在对这个问题的简短评论中提供了关键的指导:

由于您使用classes,你必须使用modules并导入它们using module https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_using声明以便使用它们。

具体来说,为了引用一个类型(类)class定义,该类型必须为 PowerShell 所知在解析时.

在你的例子中,为了导出Tesla从课堂上Car, type Car当脚本运行时,PowerShell 必须知道parsed, before执行开始 - 这就是为什么it is too late尝试导入Car通过点采购其包含的脚本 (. "$PSScriptRoot\Car.ps1")

PowerShell 通过以下两种方式之一在解析时了解引用类型:

  • 如果类型是已经加载进入当前 PowerShell 会话

  • Via a using module引用定义了类型(类)的模块的语句(请注意,还有一个using assembly用于从 DLL 加载类型的语句,以及using namespace以允许仅通过名称引用类型)。

    • 请注意,相关Import-Modulecmdlet 确实not在这种情况下工作,因为它执行于runtime.

因此,正如 PetSerAl 所建议的:

  • 将您的课程存储在module files(独立的*.psm1最简单情况下的文件)

  • Then use using module拥有Tesla模块导入Car模块和MyScript.ps1脚本导入Tesla模块,使用相对于封闭脚本/模块位置的路径.

MyScript.ps1
classes\
    Car.psm1    # Note the .psm1 extension
    Tesla.psm1  # Ditto

Car.psm1:

class Car {}

Tesla.psm1:

using module .\Car.psm1

class Tesla : Car {}

MyScript.ps1:

using module .\classes\Tesla.psm1

$tesla = [Tesla]::new()
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

点源文件中的 PowerShell 点源 - 导入类 的相关文章

随机推荐