Import and export classes from other files

时间:2019-04-08 13:34:07

标签: powershell powershell-v5.0

I'll create a PowerShell script and I'll to load some code from other files to reuse it. But when I import a file, I've this error:

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

Here is my car.psm1 file:

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

Here is how I call the code:

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

How could I do this?

I've also tried other ways to do the same but nothing is working.

1 个答案:

答案 0 :(得分:2)

Import-Module does not load class definitions.

You'll need to use the using module statement at the head of your script:

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

$car = [Car]::new()

I suggest creating modules somewhere in your $Env:PSModulePath so you don't need to fully-qualify the path in the import statement:

$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'

In use:

using module car

about_Using

Import-Module