从其他文件导入和导出 类

Import and export classes from other files

我将创建一个 PowerShell 脚本,然后从其他文件加载一些代码以重新使用它。但是当我导入一个文件时,我有这个错误:

New-Object : Cannot find type [Car]: verify that the assembly containing this type is loaded.
At C:\Repo-path\test.ps1:4 char:13
+ [Car]$car = New-Object Car;
+             ~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidType: (:) [New-Object], PSArgumentException
    + FullyQualifiedErrorId : TypeNotFound,Microsoft.PowerShell.Commands.NewObjectCommand

这是我的 car.psm1 文件:

New-Module -Script {
    class Car {
        [String]$vin;
        [String]$model;
    }
}

下面是我调用代码的方式:

Import-Module -Force "C:\Repo-path\car.psm1" ;
[Car]$car = New-Object Car;

我该怎么做?

我也尝试过其他方法来做同样的事情,但没有任何效果。

Import-Module 不加载 class 定义。

您需要在脚本开头使用 using module 语句:

using module C:\Repo-path\car.psm1

$car = [Car]::new()

我建议在 $Env:PSModulePath 中的某处创建模块,这样您就不需要完全限定导入语句中的路径:

$path = "$HOME\WindowsPowerShell\car.0"
[void](mkdir $path -Force)
'class Car { [string] $Vin; [string] $Model }' | Out-File -FilePath "$path\car.psm1"
New-ModuleManifest -Path "$path\car.psd1" -RootModule "$path\car.psm1" -ModuleVersion '1.0'

正在使用:

using module car

about_Using

Import-Module