MadBoy
MadBoy

Reputation: 11104

Method inside PowerShell class

I wanted to define class in PowerShell. Inside that class I wanted to use function defined elsewhere, so that when one asks for that value it is automatically run when needed. Following is an example of this.

class ActiveDirectoryUser {
    $DisplayName
    $LastName
    $FirstName
    $FirstNameNonLatin =  Remove-StringLatinCharacters -String $FirstName 
}

However this doesn't really work. It works in C# so what is the equivalent for this in PowerShell?

I am using this code in a way:

 $user = New-Object ActiveDirectoryUser   
 $user.DisplayName = $u.DisplayName
 $user.LastName = $u.LastName
 $user.FirstName = $u.FirstName

 $user | ft *  # should show all fields including FirstNameNonLatin 

Upvotes: 1

Views: 3151

Answers (2)

gvee
gvee

Reputation: 17161

Give this a whirl

function Get-FormattedFullName {
    Param (
        [string]
        $FirstName
        ,
        [string]
        $LastName
    )

    Process {
        return "{0} {1}" -f $FirstName, $LastName
    }

}

$ActiveDirectoryUser = New-Object -TypeName PSObject
$ActiveDirectoryUser | Add-Member -MemberType NoteProperty   -Name "FirstName" -Value "John"
$ActiveDirectoryUser | Add-Member -MemberType NoteProperty   -Name "LastName"  -Value "Smith"
$ActiveDirectoryUser | Add-Member -MemberType ScriptProperty -Name "FullName"  -Value `
    { #Get
        return Get-FormattedFullName -FirstName $this.FirstName -LastName $this.LastName
    }
`

$ActiveDirectoryUser

Results:

FirstName LastName FullName    
--------- -------- --------    
John      Smith    John Smith 

If we then update the LastName property of the object, the FullName reflects this change too:

$ActiveDirectoryUser.LastName = "CHANGED"

$ActiveDirectoryUser

Results:

FirstName LastName FullName    
--------- -------- --------    
John      CHANGED  John CHANGED

Upvotes: 1

Frode F.
Frode F.

Reputation: 54881

You need a constructor to set the default value using another property. Ex:

function Remove-StringLatinCharacters ([string]$String) { $string.Substring(0,1) }

class ActiveDirectoryUser {
    [string]$DisplayName
    [string]$LastName
    [string]$FirstName
    [string]$FirstNameNonLatin

    ActiveDirectoryUser ([string]$DisplayName, [string]$LastName, [string]$FirstName) {
        $this.DisplayName = $DisplayName
        $this.LastName = $LastName
        $this.FirstName = $FirstName
        $this.FirstNameNonLatin =  (Remove-StringLatinCharacters -String $FirstName)
    }
}

[ActiveDirectoryUser]::new("Disp","Last","First")

DisplayName LastName FirstName FirstNameNonLatin
----------- -------- --------- -----------------
Disp        Last     First     F 

Upvotes: 2

Related Questions