Monthly Archive

Categories

PowerShell classes — using methods

.NET objects usually have methods as well as properties. A method enables you to do something to or with the object.  PowerShell classes can implement methods:

class LastBoot {
[string]$ComputerName
[DateTime]$LastBootime

## methods

[TimeSpan] Uptime([datetime]$lbt)
{
$ts = (Get-Date) - $lbt
return $ts
}

## constructors
LastBoot(){}

LastBoot([string]$computer, [DateTime]$lbt) {
  $ComputerName = $computer
  $LastBootime = $lbt
}

}

$comp = $env:COMPUTERNAME
$lbtime = Get-CimInstance -ClassName Win32_OperatingSystem -ComputerName $comp |
    select -ExpandProperty LastBootUpTime

$obj = [LastBoot]::new()
$obj | gm

$obj.Uptime($lbtime)

 

A method is defined like this:

[TimeSpan] Uptime([datetime]$lbt)
{
$ts = (Get-Date) - $lbt
return $ts
}

 

Give the type of the return value and the type and name of input parameters. If you don’t give an input type System.Object is assumed.

Write the code to perform the method’s action

 

use return to return the any values from the method. If your method doesn’t return anything then use a return type of [void] in the definition.

 

You must use return with a method. You can’t just put the object on the pipeline as you would with a function.

 

PowerShell classes are still a work in progress and you may see changes when we see the next preview

Comments are closed.