Introduction
Before the holidays I had started a series on classes and objects in PowerShell. If you haven’t read my post Fun With PowerShell Classes – The Basics you should give it a quick read. There are terms that were defined in it that we’ll be using here.
For this post I’ll begin a series on the use of PSCustomObject
. Prior to the addition of classes in PowerShell 5.0, this was the technique needed to create your own customized objects. It still has a lot of validity today though, as you can use these techniques to extend the objects other people defined, including those already built into PowerShell.
In addition, understanding the use of PSCustomObject
will give you a better understanding of the way classes work.
First let me mention that for all of the examples we’ll display the code, then under it the result of our code when applicable. In this article I’ll be using PowerShell Core, 7.2.1, and VSCode. The examples should work in PowerShell 5.1 in the PowerShell IDE, although they’ve not been tested there.
Second, be on the lookout for the backtick ` , PowerShell’s line continuation character, at the end of many lines in the code samples. The blog formatting has a limited width, so using the line continuation character makes the examples much easier to read. My post Fun With PowerShell Pipelined Functions dedicates a section to the line continuation character if you want to learn more.
To run a snippet of code highlight the lines you want to execute, then in VSCode press F8 or in the IDE F5. You can display the contents of any variable by highlighting it and using F8/F5.
Code to Generate Our PSCustomObject
For these demos, I’m going to wrap the creation of our objects within a function. This is a common technique which allows us to create multiple objects based on a single set of code. Note this isn’t required, you could use these techniques anywhere in your code. I just find placing it in functions makes for greater reuse.
If you need a refresher on PowerShell functions, I’ll refer you back to my posts on functions: Fun With PowerShell Basic Functions; Fun With PowerShell Advanced Functions; and Fun With PowerShell Pipelined Functions.
Let’s take a look at our first example, then break down each line.
function Create-Object ($Schema, $Table, $Comment)
{
# Build a hash table with the properties
$properties = [ordered]@{ Schema = $Schema
Table = $Table
Comment = $Comment
}
# Start by creating an object of type PSObject
$object = New-Object –TypeName PSObject `
-Property $properties
# Return the newly created object
return $object
}
Our first line, obviously, defines our basic function. For this example I will be creating an object that holds the schema and table names for a database. It also will allow for a comment, so these are the three parameters that are passed in.
To add a list of properties to our object, we need to use a hash table. I define the hash table with three properties, Schema, Table, and Comment, and assign the parameter variables we passed in for their respective values. And yes, I do have a post on hash tables if you wish to know more about them, Fun With PowerShell Hash Tables.
Next is where the magic occurs. I call the cmdlet New-Object
. For its TypeName
parameter I use the value of PSObject
. This will create a variable of type PSCustomObject
. I then pass in my hash table name for the Property
parameter.
This is assigned to the variable $object
. In the final line I return that value to the calling code.
Before someone points it out, yes I could have made the last line of the function simply New-Object –TypeName PSObject -Property $properties
and not assigned it to a variable. As I explain in my previously mentioned posts on functions, not consuming the output within the function returns the value to the code that called it.
Assigning to a value within my function, then returning that value, gives me some additional flexibility. Primarily I could use the Write-Verbose
and Write-Debug
statements to echo additional debugging information back to the developer (or user). It also allows for easier integration with testing tools, such as Pester.
For more info on Write-Verbose and Write-Debug, see my posts Fun With PowerShell Write-Verbose and Fun With PowerShell Write-Debug.
Creating Our Custom Object
Now that we have the function created, we can call it to create our custom object. We’ll then display its properties.
$myObject = Create-Object -Schema 'MySchema' `
-Table 'MyTable' `
-Comment 'MyComment'
# Display all properties
$myObject
Result:
Schema Table Comment
------ ----- -------
MySchema MyTable MyComment
As you can see, simply running the name of our variable produces a table. Across the top are the names of our properties, below it are the values we passed into the function to use as values.
If we want to prove to ourselves this is indeed a PSCustomObject
, we can use the GetType
method.
$myObject.GetType()
Result:
IsPublic IsSerial Name BaseType
-------- -------- ---- --------
True False PSCustomObject System.Object
As you can see in the Name column, it is indeed of type PSCustomObject
!
Like any object, we can assign new values by referencing the individual properties.
$myObject.Schema = 'New Schema'
$myObject.Comment = 'New Comment'
$myObject
Result:
Schema Table Comment
------ ----- -------
New Schema MyTable New Comment
In the output, you can see the values for Schema and Comment were updated. The original value for the Table property remained unchanged.
Adding Properties One At A Time
There is an alternate method we can use to create a custom object. We can create an empty object, then use the Add-Member
cmdlet to add each property individually.
Let’s rewrite our function to use this methodology.
function Create-Object ($Schema, $Table, $Comment)
{
# Start by creating an object of type PSObject
$object = New-Object –TypeName PSObject
# Add-Member by passing in input object
Add-Member -InputObject $object `
–MemberType NoteProperty `
–Name Schema `
–Value $Schema
# Alternate syntax, pipe the object as an input to Add-Member
$object | Add-Member –MemberType NoteProperty `
–Name Table `
–Value $Table
$object | Add-Member -MemberType NoteProperty `
-Name Comment `
-Value $Comment
return $object
}
The function declaration is the same as in our first example. We then create an empty object through the line $object = New-Object –TypeName PSObject
. This object now exists, but has none of our custom properties. Yet!
Now we are going to call the Add-Member
cmdlet. Add-Member
allows us to add new properties and methods to an existing object.
The first parameter, InputObject
, is used to indicate what object we want to work with.
The next parameter is MemberType
. There are a variety of types we can add to a custom object. In this case we want to add a text property, so the correct value to use is NoteProperty
. We’ll see examples of other member types as we progress through this series.
The next two parameters are pretty self explanatory. The Name
is what we want to call this property, and Value
is the value we want it to have.
We then move on to add the Table
property. In this example I wanted to show the alternative format for using Add-Member
. You can take the object you want to add a member to, and pipe it into the Add-Member
cmdlet. I’ve done this here for the Table
property, as well as for the final property Comment
.
Using this function has identical results as the previous example.
$myObject = Create-Object -Schema 'MySchema' `
-Table 'MyTable' `
-Comment 'MyComment'
$myObject
Result:
Schema Table Comment
------ ----- -------
MySchema MyTable MyComment
So why use Add-Member
? Clearly the first example where we used a hash table to declare our property list was more compact.
Think about what we did here. We added new properties to an existing object! In this case it was a custom object we created. but this could be any PowerShell object. For example, we could have a list of file system objects returned to us by the Get-ChildItem
cmdlet. Using Add-Member
we have the ability to add new properties (and methods) to those objects.
We’ll see an example of this very thing in a future blog post, but for now let’s move on to the final section in today’s post.
Creating Property Aliases
If you’ve been in IT for any length of time, you’ve probably encountered the situation where two different groups refer to the same property by two different names. In our example, let’s say the DBA’s refer to the comment property as Comment
. They would like to use that property name when they use your script.
Your software developers though don’t think of this as the comment property, instead they call it Description
. They complain that having to use the property name "Comment" is causing a lot of coding errors.
This is one of those rare times we can make everyone happy, and we do so through the use of a property alias.
We’ll start with the same $object
variable we left off with in the previous example. We’ll then use Add-Member
to add a new alias.
Add-Member -InputObject $myObject `
-MemberType AliasProperty `
-Name 'Description' `
-Value 'Comment' `
-PassThru
Result:
Schema Table Comment Description
------ ----- ------- -----------
New Schema MyTable New Comment New Comment
The first thing to note is the MemberType
. Instead of a NoteProperty
, we are using the type AliasProperty
. This will let the Add-Member
cmdlet know we are simply adding an alternate name for an existing property.
The Name
parameter is the name for the alias. The Value
is the name of the already existing property.
You’ll also note I added a switch to Add-Member
, PassThru
. In our previous examples, leaving this off ran the code but displayed no output. If want to see the results though, you can add the PassThru
switch and the new values will be displayed in the terminal, as you saw in the Result section above.
Our alias added, you can see a new column Description
. The value under it is identical to the one for comment.
Let’s change the Description
property and see what happens.
$myObject.Description = 'The Description'
$myObject
Result:
Schema Table Comment Description
------ ----- ------- -----------
MySchema MyTable The Description The Description
As you can see, both Comment
and Description
hold the newly updated value. Your users can now use these property names interchangeably.
We can of course update our original function to add the alias at the time the object is created.
function Create-Object ($Schema, $Table, $Comment)
{
# Build a hash table with the properties
$properties = [ordered]@{ Schema = $Schema
Table = $Table
Comment = $Comment
}
# Start by creating an object of type PSObject
$object = New-Object –TypeName PSObject `
-Property $properties
Add-Member -InputObject $object `
-MemberType AliasProperty `
-Name 'Description' `
-Value 'Comment'
# Return the newly created object
return $object
}
$myObject = Create-Object -Schema 'MySchema' `
-Table 'MyTable' `
-Comment 'MyComment'
$myObject
Result:
Schema Table Comment Description
------ ----- ------- -----------
MySchema MyTable MyComment MyComment
As you can see, the function generated an object that included our alias. In this example I also combined methods. I used a hash table to define our initial set of properties, then used Add-Member
to add the alias. I could have also put the addition of the alias in the second version of the function, where each property was added one at a time.
Conclusion
In this post we learned how to create a basic object using PSCustomObject. We added some properties, and even created an alias for one.
Now you may be asking "what about methods? Object can have methods too!" And you would be correct. In the next post in the series we’ll see how to add custom methods to our object.
In future posts we’ll see how to create custom objects from bits of C# code. Then we’ll see how to add our own properties and methods to an existing object created by PowerShell.
We’ll then return to our discussion of PowerShell classes by looking at some advanced features of the built in PowerShell class type.
The demos in this series of blog posts was inspired by my Pluralsight course PowerShell 7 Quick Start for Developers on Linux, macOS and Windows, one of many PowerShell courses I have on Pluralsight. All of my courses are linked on my About Me page.
If you don’t have a Pluralsight subscription, just go to my list of courses on Pluralsight . At the top is a Try For Free button you can use to get a free 10 day subscription to Pluralsight, with which you can watch my courses, or any other course on the site.