Simple examples of Powershell PSCustomObject

In most of my Powershell scripts I make use of the PSCustomObject to store results. The example I first learned (and use all the time) looks just like this:

[cc lang=”Powershell”]
$item = “” | Select Name, RAM, CPU
$item.Name = “blah”
$item.Ram = 4096
$item.Cpu = 1

In the above example, you create a blank PSCustomObject on line 1 which has Name, RAM and CPU placehoders. Then on lines 2 through 4 you assign values to each attribute. Finally on line 5 you do something with the variable $item. In the above example, the contents of the $item variable are displayed onscreen. Normally you’d see something like $myreport += $item which stores the new item in a collection called $myreport.

The problem is adding an additional attribute to your object requires two steps — first, you must declare the attribute on line 1 and then assign something to the attribute after it is declared. For example, if I wanted to add PowerState to my report, I would have to add “, PowerState” on the first line. If you forget, which happens to me all the time, you get this error:

$item.PowerState = "PoweredOff"
Property 'PowerState' cannot be found on this object; make sure it exists and is settable.
At line:1 char:7
+ $item. <<<< PowerState = "PoweredOff"
    + CategoryInfo          : InvalidOperation: (:) [], RuntimeException
    + FullyQualifiedErrorId : PropertyAssignmentException

I recently found a new example that I like a lot better. Here is an example:

[cc lang="Powershell"]
$item2 = new-object -type PSObject -Property @{
Name = "blah"
RAM = 4096
CPU = 1

In the above example, attributes are created as needed, removing the need to pre-define them on the first line of the script. This method removes the need to specify "$item." for each attribute, making the code easier to read/maintain/support.

This is a very simple example, but I hope others find it useful.

This entry was posted in Scripting. Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *