Beta 42

Research and Development

Menu

PowerShell - Creating Custom Objects

If you want to create your own custom objects, for example, to enable your functions to return rich objects, you can always use Select-Object cmdlet.

PS> $newobject = 'dummy' | Select-Object -Property Name, ID, Address

Then, you can fill in the properties and use the object:

PS> $newobject = 'dummy' | Select-Object -Property Name, ID, Address
PS> $newobject.Name = $env:username
PS> $newobject.ID = 12
PS> $newobject
Name                                                     ID Address
---- -- -------
Tobias                                                   12

In PowerShell v2, there has been an alternate way using hash tables and New-Object. This never worked well, though, because a default hash table is not ordered, so your new objects used random positions for the properties.

In PowerShell v3, you can create ordered hash tables and easily cast them to objects. This way, you can create new custom objects and fill them with data in just one line of code:

PS> $newobject = [PSCustomObject][Ordered]@{Name=$env:Username; ID=12; Address=$null}
PS> $newobject
Name                                                     ID Address
---- -- -------
Tobias                                                   12