gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 13:20:04 29 4
gpt4 key购买 nike

我的项目结构如下:

MyScript.ps1
classes\
Car.ps1
Tesla.ps1

Car.ps1 是 Tesla.ps1 的基类。我试图在 Tesla.ps1 中这样定义特斯拉:
. "$PSScriptRoot\Car.ps1"

class Tesla : Car
{
}

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

$tesla = [Tesla]::new()

点源到 classes\Tesla.ps1工作正常,但是从 Tesla 文件中抛出了这个错误:

Unable to find type [Car]



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

$tesla = [Tesla]::new()

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

最佳答案

PetSerAl就像以前无数次一样,在对这个问题的简短评论中提供了关键的指示:

由于您使用类,您必须使用模块并使用 using module 导入它们。声明 为了使用它们。

不幸的是,在撰写本文时,using module Get-Help about_Modules 中仍未提及)。

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

在您的示例中,为了导出 Tesla来自类(class)Car , 输入 Car在解析脚本时,PowerShell 必须知道,然后才开始执行 - 这就是 的原因尝试导入为时已晚Car通过点源其包含的脚本 (. "$PSScriptRoot\Car.ps1")

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

  • 如果该类型已加载到当前 PowerShell session 中
  • 通过 using module引用定义了类型(类)的模块的语句(请注意,还有一个 using assembly 语句用于从 DLL 加载类型,以及 using namespace 以启用仅通过名称引用类型)。
  • 注意相关的Import-Module cmdlet 在这种情况下不起作用,因为它在运行时执行。

  • 因此,正如 PetSerAl 建议的那样:
  • 将您的类存储在模块文件中 (最简单情况下的独立 *.psm1 文件)
  • 那么使用 using module 拥有Tesla模块导入Car模块和 MyScript.ps1脚本导入 Tesla模块,使用 相对于封闭脚本/模块位置的路径 .
  • 警告 : 从 PowerShell Core 6.1.0-preview.4 开始,有一个 bug 这要求您使用 \作为 using module 的相对路径中的路径分隔符,即使在类 Unix 平台上,您通常会使用 / .

  • 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()

    关于点源文件中的 PowerShell 点源 - 导入类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51622808/

    29 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com