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 {

## methods

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

## constructors

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



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 retrun 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

This entry was posted in PowerShell v5. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s