Removing Items FromArrays
There’s no doubt that arrays are incredibly useful when writing system administration scripts. There’s even less doubt (assuming you can haveless doubt than no doubt) that Windows PowerShell makes it very easy to work with arrays; to that end, we’ve talked about different tricks you can do with arrays in several of our previous Tips of the Week. Nevertheless, the array class built into Windows PowerShell does have at least one weakness: as easy as it might be to add a new item to an array, there’s no comparably-easy way to remove an existing item from an array. That’s a shame, but, then again, that’s just the way it goes. After all, you have to use the array class built right into Windows PowerShell, don’t you?
Using the .NET Framework ArrayList Class
You already figured out the answer to our question, didn’t you? Do you haveto use the array class built into Windows PowerShell? Of course not.After all, Windows PowerShell provides complete access to the .NET Framework, and the .NET Framework offers all sorts of alternative arrays, collections, and hash tables. Don’t like the array class built into Windows PowerShell? Then just use a different array type.
Good point: whichdifferent array type are we supposed to use? Well, one array type that’s worth investigating is the System.Collections.ArrayList class. To use this array type, all we have to do is use the New-Objectcmdlet to create a new instance of the ArrayListclass, an instance that we’ve named $a:
That command gives us an empty array named $a. If we then want to populate that array with some information (which we probably do), all we have to do is call the Addmethod followed by the item we want to add to the array. For example, here is a series of commands that adds six different color names to our array: