Creating objects using New-Object in Powershell

Since Powershell is an object-based scripting language, it is important to know how to create objects to store, modify and return information.

The New-Object cmdlet simply allows you to create an object.

Creating a .NET Object

You can either create an existing object type, for instance:

$version = New-Object -TypeName System.Version -ArgumentList "2.0.2.1"
PS C:\WINDOWS\system32> $version

Major  Minor  Build  Revision
-----  -----  -----  --------
2      0      2      1       

This has created a System.Version object. We can see this by inspecting the type of the resulting object:

PS C:\WINDOWS\system32> $version.GetType()

IsPublic IsSerial Name     BaseType
-------- -------- -------- --------    
True     True     Version  System.Object       

Creating a custom object

You can also create a custom object, by setting the -TypeName parameter to PSObject, and then passing the properties in using the -Property parameter:

$MyDetails = @{
Name = 'Sean'
Height = '188cm'
}

$Me = New-Object -TypeName PsObject -Property $MyDetails
PS C:\WINDOWS\system32> $Me

Height Name
------ ----
188cm  Sean

Hashtables vs PSCustomObjects

But wait, we already created something called $MyDetails that contains all of the object data, why did we need to create a new object?

Let's inspect the type of both:

PS C:\WINDOWS\system32> $MyDetails.GetType()

IsPublic IsSerial Name      BaseType
-------- -------- --------- --------    
True     True     Hashtable System.Object       


PS C:\WINDOWS\system32> $Me.GetType()

IsPublic IsSerial Name           BaseType
-------- -------- -------------- --------    
True     True     PSCustomObject System.Object       

The details that were passed into the -Property parameter were in the form of a hashtable.

The object however, is of type PSCustomObject.

Something we can do with an object that we cannot do with a hashtable, is add additional members after it has been created:

$Me | Add-Member -MemberType NoteProperty -Name Age -Value '30'
PS C:\WINDOWS\system32> $Me

Height Name  Age
------ ----  ---
188cm  Sean  30