我的项目结构如下:
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 通过以下两种方式之一在解析时了解引用类型:
因此,正如 PetSerAl 所建议的:
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(使用前将#替换为@)