Defining and changing who you are with PowerShell classes and Update-List

Folks, I will not lie to you. When I received my topic assignment and saw “Update-List” next to my name, I had absolutely no idea what cmdlet that was. I have never used it and never heard of it, which makes learning and writing about it challenging and fun.

Update-List is a pretty cool way to add, remove and replace values in a collection, which I find particularly useful when working within the property of a class.

Without further ado, lets get do it.

Defining yourself

To best illustrate Update-List, lets first set up a simple class. This class is about Dad’s. Well, who are Dad’s? Dad’s have a first name, last name, an age, some hobbies, a mood, and kids of course.

You will notice that I chose to use a generic list for my hobbies and kids. You will see later that this is where Update-List comes in handy. With Update-List, we can easily change the values in these properties. Whenever I have had to write PowerShell scripts that need to change the values of an array, a generic list is what I have used in the past.

Now that we have defined what a “Dad” is, lets instantiate one of these bad boys.

Neat. Now lets give $Dan some values:

There we go. I am a Dad that has a first name, last name, hobbies, kids, age and a mood (angry).

Now we know who I am. I have defined myself pretty well I would say.

Changing who you are

Lets face it, people change. We are not static beings that keep the same state forever. So what can do I do to change who I am? We can use Update-List of course.

We know that I likes golf and dancing as hobbies, but you know what? I have just turned 40 (hypothetically) and realize it hurts like heck when I try to tango. So first we will just change the value of my age.

Now, lets get rid of dancing as a hobby since I am getting old.

Next, lets use Update-List to add two values to my hobbies, beer and couching. If you are wondering what “couching” is, this term refers to sitting on the couch as long as you can without performing any productive task whatsoever.

After a while of couching, I realize its time to do choose something more productive to do with my time. I think I will take up golf but still enjoy my alone time with a cocktail every now and then. Here we completely replace the values in the hobbies property with golf and cocktails, subsequently removing beer.

Hmm, you know what? My kids have been driving me insane. Let’s replace them as well:

Look at me, I have changed so much of who I am today!
As you can see, Update-List is a great way to manage values when working with a generic list within classes.

Leave a Reply

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