The output will now include our new custom property called
I had to change the code quite a bit so allow me to break it down. First, notice how I moved the original properties being passed to
IPV4Address,ResponseTime,TimeToLive) above, then passed
Select-Object that way. This was simply to reduce the length of the line. It behaves exactly the same as if I simply passed them directly to
Select-Object as I did in the console previously.
What functionality did change was the addition of another property in
$selectProperties to pass to
Select-Object. Notice it wasn't a string like the others but a hashtable with two elements inside:
Expression. This is called a calculated property. This is how using
Select-Object you can essentially create properties on the fly. Every property you'd like to add has to be in a hashtable with a
Name and an
Expression as key names. The
Name key's value is the name you'd like to call the object property. The
Expression key's value always has to be a script block. Notice
$serverName is enclosed in curly braces. This is how
$serverName can be expanded to the actual server names as each server is tested in the text file.
This can be used not only to create new properties but to modify existing properties as well. Maybe I'd like to append a
ms label to all the
TimeToLive properties to signify the number is in milliseconds. Instead of specifying the name of the
TimeToLive property I would instead create a hashtable and concatenate the
foreach pipeline value of
TimeToLive represented by
ms to create a single string.
Using calculated properties with
Select-Object are very convenient but beware: They come with a performance hit. I don't recommend using calculated properties if you're working with large data sets as it can drastically slow down your script. But if you have fairly small data sets with 100 or fewer elements the performance hit will be minimal.
Custom object creation
Objects abound in PowerShell, and it only makes sense for us to be able to create our own objects from scratch. Fortunately, PowerShell provides us with a few different ways to do that. In this tip, I'll cover three methods to create custom objects.
In PowerShell, an object is of a specific type. When creating custom objects, the most common type of object type is
System.Management.Automation.PSCustomObject. This is the kind of object we'll create in this article. Also, an object has one or more properties of various types. In this article, we'll focus on
Sign up for Computerworld eNewsletters.