Most of the time, the bulk of new object is static data, represented by properties. A highly efficient way to create new objects with new properties is converting hash tables to objects – we covered this earlier:

$conf = [PSCustomObject]@{
    Name = 'Tobias'
    Conf = 'psconf.eu'
    Url = 'http://psconf.eu'
}

The result is a simple object with no specific methods at all:

 
PS C:\> $conf 

Name   Conf      Url             
----   ----      ---             
Tobias psconf.eu http://psconf.eu
 

To add methods, next you use Add-Member and refine the object. This line adds a new Register() method:

$object | 
  Add-Member -MemberType ScriptMethod -Name Register -Value { Start-Process -FilePath $this.url }

Note how the script block invoked by the Register() method accesses $this: the $this variable represents the object itself, so Register() will continue to work even if you later decide to change the “Url” property..

When you run Register(), the object opens the URL specified in the “Url” property:

 
PS C:\> $conf.Register()
 

Twitter This Tip! ReTweet this Tip!

Anonymous