如何从单独的 ps1 文件访问自定义 PowerShell 5.0 类

use*_*178 6 powershell module class

我在 ps1 文件中创建了一个类,该类在 ps1 文件本身中工作得很好。我可以在同一个文件中使用类和测试运行各种测试。

我的麻烦是我似乎无法找到一种方法将我的类放入一个文件中并将类使用代码放入另一个文件中。

使用函数,您只需点源它们即可将任何外部 ps1 文件引入当前脚本中。看起来 Powershell 的类不能以这种方式工作。

如何组织代码以将类保存在与执行脚本不同的文件中?

我必须使用模块吗?我怎么做?

小智 4

在文件中Hello.psm1

class Hello {
# properties
[string]$person

# Default constructor
Hello(){}

# Constructor
Hello(
[string]$m
){
$this.person=$m
}

# method
[string]Greetings(){
return "Hello {0}" -f $this.person
}

}
Run Code Online (Sandbox Code Playgroud)

在文件中main.ps1

using module .\Hello.psm1

$h = New-Object -TypeName Hello
echo $h.Greetings()
#$hh = [Hello]::new("John")
$hh = New-Object -TypeName Hello -ArgumentList @("Mickey")
echo $hh.Greetings()
Run Code Online (Sandbox Code Playgroud)

并运行.\main.ps1

Hello 
Hello Mickey
Run Code Online (Sandbox Code Playgroud)