In the previous post of my series about PowerShell classes, I introduced the property concept. In today's post, I will show you how to define methods and explain the concepts of static methods and method overloads.

An object’s methods determine its possible actions. A method is somewhat similar to a function in that it executes a procedure; the main difference is that the method is attached to the object. In contrast to methods, properties contain data only.

In my example, I will use two different methods. The first will create a user object in Active Directory using the New-ADUser cmdlet, and the second one will generate a unique user name.

Defining a method

A method has the following syntax:

[ReturnType]<MethodName>([Type]Parameter1,[Type]Parameter2){
}

In the example below, I define the create method, which is attached to the employee class that I introduced in my previous post.

Class Employee {

    [ValidatePattern("^[a-z]+$")]
    [string]$FirstName
    [ValidatePattern("^[a-z]+$")]
    [string]$LastName
    hidden [string]$UserName
    [ValidateSet('Internal','External')]
    [string]
    $EmployeeType
    [ValidatePattern("^OU=")]
    [string]$OU
    hidden static [string]$DomainName = "DC=District,DC=Local"

[Employee]Create(){
        
        New-ADUser -SamAccountName $this.UserName `
                   -GivenName $this.FirstName `
                   -Surname $this.LastName `
                   -Name $this.UserName `
                   -UserPrincipalName $this.UserName `
                    -DisplayName ($this.FirstName + " " + $this.LastName) `
                    -Description ($this.FirstName + " " + $this.LastName) `
                    -Path $this.OU

        return $this
    }
}

The keyword $this is a reference to the object’s current instance. Each time we create a new instance of our class and save into a variable, the class can access its own properties and methods using this special keyword. Thus, $this.UserName refers to the property value of UserName that has been set in the instance of the current object.

Notice the return type of the method. In this particular case, we are returning the complete instance of our class employee using the keyword $this again.

The second method generates a new user name in Active Directory (SamaAccountName), which has to be unique. For this, we will take the first letters of the user's last name, add the two first letters of his first name, and then add a two-digit number after it.

A new employee named "Stéphane van Gulick" would get the user name Vangust01. If a second Stéphane van Gulick joined the company (I have actually never met another Stéphane van Gulick), the name would be vangust02, and so on.

This method has a bit more logic than the first. It will generate a user account name and scan through the AD to search if the name has already been taken. If it already exists, the two-digit number will be incremented by one, and the new user name will be returned.

[string]static GetNewUserName([string]$FirstName,[string]$LastName){

        $start = $LastName.replace(" ","").Substring(0,5)
        $end = $FirstName.Substring(0,2)
        
        
            $UName = ($start + $end).ToLower()
        
        
            $AllNames = Get-ADUser -Filter "SamaccountName -like '$UName*'"
            [int]$LastUsed = $AllNames | % {$_.SamAccountName.trim($Uname)} | select -Last 1
            $Next = $LastUsed+1
            $nextNumber = $Next.tostring().padleft(2,'0')
            $SamAccountName = $UName + $nextNumber
        return $SamAccountName
         
        
}

In this case, the return type of our message is [string] (because the content of SamAccountName is going to be a string).

Static methods

The keyword static will make this method available without the need to create an instance of the object. This means we can call it directly from our class like this:

[Employee]::GetNewUserName("Stephane","vanGulick")

Methods, just like properties, can also be called directly through the class, without being set to an instance. You can discover static methods in the same way as static properties by using the  -Static parameter of the Get-Member cmdlet:

$NewEmployee | Get-Member -static
Discovering static methods

Discovering static methods

If you want to dig more into static methods or if you want to see another example, I recommend you read this article.

Method overloading

We now have a method that gets the next available user name in Active Directory. Let's say you need a slightly different method. For example, you might need a method that returns a user name with a different number of letters. In this case, you can create a method overload. We get access to the same functionality, but with a slightly different flavor.

Methods are particular to a specific type of object. However, you can work with methods that have the exact same name if they have a different signature. The signature of a method corresponds to the number of parameters and their types that the method accepts. For instance, this is the signature of our method GetNewUserName from above:

[string]$FirstName,[string]$LastName

The two strings as parameters generate a specific signature. In the following method, I use the same code, but this time with three parameters. This time, the signature consists of two strings and one integer. The integer I added as a parameter $Length will allow us to specify the number of letters of the last name.

[string]static GetNewUserName([string]$FirstName,[string]$LastName,[int]$Length){

        $start = $LastName.replace(" ","").Substring(0,$Length)
        $end = $FirstName.Substring(0,2)
        
        
            $UName = ($start + $end).ToLower()
        
        
            $AllNames = Get-ADUser -Filter "SamaccountName -like '$UName*'"
            [int]$LastUsed = $AllNames | % {$_.SamAccountName.trim($Uname)} | select -Last 1
            $Next = $LastUsed+1
            $nextNumber = $Next.tostring().padleft(2,'0')
            $SamAccountName = $UName + $nextNumber
        return $SamAccountName
         
        
}

If we call our static methods one after the other, we will have the following results:

[employee]::GetNewUserName("Stephane","vangulick")
[employee]::GetNewUserName("Stephane","vangulick",4)
Calling our static methods

Calling our static methods

The first method generated the samaccountName vangust01 (5+2 letters) and the second method we added the number 4 as our third and last parameter. It then generated the SamAccountName vangst01 (4+2 letters). So you see, it is essentially the same method, but with a different input (three instead of two parameters) and a slightly different output.

Subscribe to 4sysops newsletter!

If you want to dive a bit deeper in methods, and learn about method overloading and overriding, I recommend you read this article. I’ll see you in the next post in this series about PowerShell classes, where I will be covering the basics of constructors.

avatar
1 Comment
  1. JG 5 years ago

    This is a very informative series, but one thing which I feel is lacking is that you don’t cover how to import class from a module in a separate file (via the “using module” keyword). I spent a lot of time searching for this command as it was not inherently obvious and I feel as though it is important information to have.

Leave a reply

Your email address will not be published. Required fields are marked *

*

© 4sysops 2006 - 2023

CONTACT US

Please ask IT administration questions in the forums. Any other messages are welcome.

Sending

Log in with your credentials

or    

Forgot your details?

Create Account