Emulating a class with methods in a module

 ̄綄美尐妖づ 提交于 2019-12-12 13:39:00

问题


I am using PowerShell 2.0 (can't upgrade) and I am writing a series of scripts that uses some information from Active Directory. Coming from an OOP languages like C++, I want to emulate a class in PowerShell 2.0, but I know that they only have the class statement in 5.0, and I don't want to use C# to embed classes because I already have a functions (which will be my methods) written in Powershell..

I read this: Powershell. Create a class file to hold Custom Objects?

And I am able to do a function creating a PSObject with "members", but not sure how to make it work with methods so that I can just load the function in my scripts to have a cleaner code.

This is what I have so far:

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

}

How I can do this so that I just have this function loaded in my script?

Thanks!


回答1:


ScriptMethods could fill the gap you are looking for here. Assuming the object has a property for firstname and lastname you could do something like this.

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

Then with the returned object you can call the scriptmethod samaccountname

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

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

Which would return "mbagel". This was tested on 2.0.

So if you wanted to use a function in the method that is just a matter of making sure it is sourced ahead of the time it is called.

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}

If you want these things available all the time then you just need to load them into a PowerShell profile.



来源:https://stackoverflow.com/questions/35943179/emulating-a-class-with-methods-in-a-module

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!