Add custom method to custom object

Hello,

In a previous post, we saw how to create PowerShell Objects.

Today, we’ll see how to add custom methods to custom PowerShell object :

Add-Member -memberType ScriptMethod -InputObject $Computer -Name "Ping" -Value {Test-Connection -ComputerName $this.Name -Quiet -Count 1 } -Force
$Computer.Ping()
$Computer | Get-Member

The first line adds the method to our object, the second one execute it, and the third shows us the object, with the function in it :

PowerShell-Object-CustomMethod

If we create an ‘ItForDummies.Compter’ object with a dummy computer name :

$DummyComputer = [PsCustomObject][Ordered]@{Name = "DoesNotExists"; State = "Unknown"; OS = "Unknown"; PsTypeName ='ItForDummies.Computer'}
Add-Member -memberType ScriptMethod -InputObject $DummyComputer -Name "Ping" -Value {Test-Connection -ComputerName $this.Name -Quiet -Count 1 } -Force
$DummyComputer.Ping()

PowerShell-Object-CustomMethod-PingFailed

The ping failed.

As you can see, we need to add the method to all objects we create. The good way to do this is to add the method to the type, and not the object :

$Ping = @{
    MemberName = 'Ping'
    MemberType = 'ScriptMethod'
    Value = {Test-Connection -ComputerName $this.Name -Quiet -Count 1 }
    Force = $true
}
Update-TypeData -TypeName 'ItForDummies.Computer' @Ping
$NewComputer = [PsCustomObject][Ordered]@{Name = "localhost"; State = "Unknown"; OS = "Unknown"; PsTypeName ='ItForDummies.Computer'}
$NewComputer.Ping()

PowerShell-Object-CustomMethod-OnCustomType

All new ‘ItForDummies.Computer’ objects with have the “Ping()” method.

That’s pretty nice, but you can go further. You noticed that the ‘ItForDummies.Computer’ has a ‘State’ property ?

Look at  this :

$Ping = @{
    MemberName = 'Ping'
    MemberType = 'ScriptMethod'
    Value = {if(Test-Connection -ComputerName $this.Name -Quiet -Count 1){$this.State = "Online"}else{$this.State = "Offline"}}
    Force = $true
}
Update-TypeData -TypeName 'ItForDummies.Computer' @Ping
$OnlineComputer = [PsCustomObject][Ordered]@{Name = "localhost"; State = "Unknown"; OS = "Unknown"; PsTypeName ='ItForDummies.Computer'}
$OnlineComputer.Ping()
$OnlineComputer
$OfflineComputer = [PsCustomObject][Ordered]@{Name = "DoesNotExist"; State = "Unknown"; OS = "Unknown"; PsTypeName ='ItForDummies.Computer'}
$OfflineComputer.Ping()
$OfflineComputer

PowerShell-Object-CustomMethod-2

The property ‘State’ actualize after calling the ‘Ping()’ method !

Leave a Reply