从其他文件导入和导出类

问题描述 投票:1回答:1

我将创建一个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;

我怎么能这样做?

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

powershell powershell-v5.0
1个回答
2
投票

Import-Module不加载类定义。

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

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

$car = [Car]::new()

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

$path = "$HOME\WindowsPowerShell\car\1.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

最新问题
© www.soinside.com 2019 - 2024. All rights reserved.