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

标签 powershell class module

我在 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/

相关文章:

powershell - 如果不合格,如何创建一个 powershell 函数来扩展文件名参数以包含它们的路径?

powershell - 如何在PowerShell中使用GUI使用最大化组框?

windows - Powershell,如何获取上次 Windows 更新安装日期或至少检查更新?

windows - Powershell get-childitem 输出格式

c++ - 在预期非成员函数指针时传递成员函数指针?

node.js - 从对象发出事件

perl - 未知指令 "perl_modules"

java - 如何正确返回从类扩展并实现接口(interface)的东西?

Java - 如何将从一个类的方法中生成的变量传递到另一个类?

c - 通过 netlink 从内核向用户空间单播数据时失败