我在 ps1 文件中创建了一个类,该类在 ps1 文件本身中工作得很好。我可以在同一个文件中使用类和测试运行各种测试。
我的麻烦是我似乎无法找到一种方法将我的类放在一个文件中,而将类使用代码放在另一个文件中。
使用函数,您只需点源它们即可将任何外部 ps1 文件带入当前脚本。看起来 Powershell 的类不能以这种方式工作。
如何组织代码以将类保存在与执行脚本不同的文件中?
我必须使用模块吗?我怎么做?
最佳答案
在文件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
}
}
在文件
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()
并运行
.\main.ps1
:Hello
Hello Mickey
关于powershell - 如何从单独的 ps1 文件访问自定义 PowerShell 5.0 类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48050521/