My Technical Notes

Sunday, 20 December 2015

PowerShell: Creating custom objects

In PowerShell, you can create custom objects fairly easily. First you create a `PSCustomObject` by using `New-Object`:


$person = New-Object PSObject

Thereafter you can add properties to the object (note that I am using the command's default parameter order):


$person | Add-Member NoteProperty Forename "Tahir"
$person | Add-Member NoteProperty Surname "Hassan"

Lastly, we can add a method (here I am using backtick which is the line continuation character here). Note the use of `$this` to refer to self.


$person | Add-Member ScriptMethod FullName `
          { $this.Forename + " " + $this.Surname }

Calling `FullName` method:


$person.FullName()
outputs

Tahir Hassan

No comments: