header image

PowerShell 5.0 – – classes

Posted by: | October 25, 2014 Comments Off on PowerShell 5.0 – – classes |

I’ve shown this method of creating a new object several times:

 

$source = @"
public class LastBoot
{
  public string ComputerName {get; set;}
  public string LastBootime {get; set;}
}
"@

Add-Type -TypeDefinition $source -Language CSharpVersion3

$computer = $env:COMPUTERNAME

$props = [ordered]@{
  ComputerName = $computer
  LastBootime = Get-CimInstance -ClassName Win32_OperatingSystem -ComputerName $computer |
    select -ExpandProperty LastBootUpTime
}

New-Object -TypeName LastBoot -Property $props

 

Define a class in C# – in this case a simple class that has 2 properties ComputerName and LastBootime which are both strings for simplicity.  Compile the code via Add-Type

 

Define the value of the properties in a hash table and create an object.

 

This approach has a number of benefits – you have given your object a distinct type so you can easily create format and type data for it. Also the properties are strongly typed which means if to try to define a property with a value that isn’t of the correct type or can’t be converted into the correct type the creation will fail.

 

The drawbacks are that you have to use C# to define the class and Add-Type won’t let you redefine the class in the PowerShell session in which you create it.

 

The drawbacks, especially the first one, put most peopel off from using this approach.

 

PowerShell 5.0 has simplified working like this as you can now create classes directly in PowerShell.

 

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

$obj = [LastBoot]::new()

$obj.ComputerName = $env:COMPUTERNAME
$obj.LastBootime = Get-CimInstance -ClassName Win32_OperatingSystem -ComputerName $computer |
    select -ExpandProperty LastBootUpTime

$obj

 

Use the class keywaird to start the class definition. The properties are defined in a similar way to advanced functions – note there isn’t a comma after the function.

 

A new instance is created like this:

$obj = [LastBoot]::new()

 

You can’t use New-Object in the latest version of PowerShell 5.0  – I presume that will be added at some thime.

 

You can then populate the properties and output the object.

 

This is just scratching the surface with classes. This whole addition will make working with new objects more flexible as you can easily define what you want your output object to be like and then PowerShell will enforce the property types for you.

In case you were wondering use LastBootime was deliberate  Smile

under: PowerShell v5

Comments are closed.

Categories