我将创建一个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
不加载类定义。
您需要在脚本的头部使用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