header image

PowerShell classes — using methods

Posted by: | October 27, 2014 Comments Off on 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 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

under: PowerShell v5

Comments are closed.