【问题标题】:Emulating a class with methods in a module使用模块中的方法模拟类
【发布时间】:2016-06-26 20:57:01
【问题描述】:

我正在使用 PowerShell 2.0(无法升级)并且我正在编写一系列脚本,这些脚本使用来自 Active Directory 的一些信息。来自像 C++ 这样的 OOP 语言,我想在 PowerShell 2.0 中模拟一个类,但我知道它们在 5.0 中只有 class 语句,我不想​​使用 C# 来嵌入类因为我已经有一个用 Powershell 编写的函数(这将是我的方法)..

我读到这个:Powershell. Create a class file to hold Custom Objects?

而且我可以使用“成员”创建一个 PSObject 的函数,但不确定如何使其与方法一起使用,以便我可以在脚本中加载该函数以获得更简洁的代码。

这是我目前所拥有的:

function New-User {

    param($user,
         $headers = @("header1","header2","header3","header4") )

    $new_user = New-Object -TypeName PSObject
    foreach ($header in $headers){
        $new_user | Add-Member -membertype NoteProperty -name $header -value $user.$header
    }
   $new_user | Add-Member -membertype NoteProperty -name "othermember" -value ""
   $new_user.PSObject.Typenames.Insert(0,"AD-User")

   # Add methods here! for example:
   $new_user | Add-Member -membertype METHOD -name "othermember" -value     MYDEFINED_FUNCTION($new_user.header1)


   return $new_user

}

我怎样才能做到这一点,以便在我的脚本中加载这个函数?

谢谢!

【问题讨论】:

  • 如果您真的想要一门课程,您是否在该问题的标记答案中查看了 Add-Type。除此之外,您可能会更轻松地使用脚本方法,并确保在使用“类”之前获取您的函数。
  • 嗨,您只想在“某处”声明一次,然后在脚本中添加一个“包含”?
  • 是的,我想将其声明为“模块”或只是一个文件,我可以在其中加载脚本中的模拟类。例如,如果类文件名是 class.ps1,那么我可以执行类似 $user = New-User(param1,param2,param3) 的操作
  • @Matt 是的,但是我不想嵌入 C# 代码(可以快速学习,但仍然需要将代码重写为 C#)。你能给我一个使用脚本方法的例子吗?这应该在自包含文件中,以便我可以将其加载到我的脚本中。

标签: oop powershell powershell-2.0


【解决方案1】:

ScriptMethods 可以填补您在这里寻找的空白。假设该对象具有 firstnamelastname 的属性,您可以执行类似的操作。

$new_user | Add-Member -membertype ScriptMethod -name samaccountname -value  {$this.firstname.substring(0,1) + $this.LastName}

然后使用返回的对象,您可以调用scriptmethod samaccountname

$matt = New-Object -TypeName psobject -Property @{
    firstname = "matt"
    lastname = "bagel"
}

$new = new-user $matt "firstname","lastname"
$new.samaccountname()

这将返回“mbagel”。这是在 2.0 上测试的。

因此,如果您想在方法中使用函数,只需确保在调用它之前就已获取该函数。

function Get-AccoutName{
    param(
        [string]$firstname,
        [string]$lastname
    )

    $firstname.substring(0,1) + $lastname
}
.....
other code you have
.....
$new_user | Add-Member -membertype ScriptMethod -name samaccountname -value  {Get-AccoutName $this.firstname $this.LastName}

如果您希望这些东西一直可用,那么您只需将它们加载到 PowerShell 配置文件中。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-12-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-25
    • 1970-01-01
    相关资源
    最近更新 更多