Jan 122011
 

Have you ever worked with arrays and felt you weren’t able to put in all the data you wanted? Have you tried making two arrays and syncing all the data between the two? Sometimes you just need to store more than one thing. The answer is to make your own custom object, and then put that into the array. It really is easier than you might think.

First, you need to make a new system object. To do this we’ll use the New-Object command. Now if you know what type of object, as defined by .NET, that you would like to create, then you can specify it here. But the point here is that we want to make our own object. So we can make a generic, blank “object” by using a system.object.

$myObject = New-Object System.Object

This makes a new object, but a new object isn’t really anything at all. Think of an object as just that, something that you can feel, that is tangible. If I were to tell you that you were holding an object, what would that mean to you? Probably nothing until you had some idea of what it was. Let’s pretend that what I just handed you is a user’s workstation, now this object has some meaning,but past giving it a name,we still haven’t defined what the object really is. Objects have properties that define them. In the case of a computer there are things like its manufacturer, how fast its processor is, and how much memory it has. So we want to track all of that in our object.

In Powershell what we need to do is add these properties to our object. We can do this with the Add-Member command. We need to tell it what type of property we are adding, what it’s called and what its value is.

$myObject | Add-Member -type NoteProperty -name Name -Value "Ryan_PC"
$myObject | Add-Member -type NoteProperty -name Manufacturer -Value "Dell"
$myObject | Add-Member -type NoteProperty -name ProcessorSpeed -Value "3 Ghz"
$myObject | Add-Member -type NoteProperty -name Memory -Value "6 GB"

Now we have a full object. It contains several properties that serve to define it and seperate it from other objects, even other PCs. We can work with the object in Powershell by calling it as a whole or by grabing any single property.

> $myObject

Name     Manufacturer   ProcessorSpeed   Memory
----     ------------   --------------   ------
Ryan_PC  Dell           3 Ghz            6 GB

> $myObject.Memory

6GB

> Test-Connection $myObject.Name -quiet

True

> $myObject.Manufacturer = "HP"
> $myObject

Name     Manufacturer   ProcessorSpeed   Memory
----     ------------   --------------   ------
Ryan_PC  HP             3 Ghz            6 GB

So now that you have this really cool object and can work with, you will of course want to have many, many more, and keep them well organized and in one place.  You can do this, and it too is very easy.  Simply take your custom objects, and put them into an array.  To show you, lets first make two more objects.

$myObject2 = New-Object System.Object

$myObject2 | Add-Member -type NoteProperty -name Name -Value "Doug_PC"
$myObject2 | Add-Member -type NoteProperty -name Manufacturer -Value "Dell"
$myObject2 | Add-Member -type NoteProperty -name ProcessorSpeed -Value "2.6 Ghz"
$myObject2 | Add-Member -type NoteProperty -name Memory -Value "4 GB"

$myObject3 = New-Object System.Object

$myObject3 | Add-Member -type NoteProperty -name Name -Value "Julie_PC"
$myObject3 | Add-Member -type NoteProperty -name Manufacturer -Value "Compaq"
$myObject3 | Add-Member -type NoteProperty -name ProcessorSpeed -Value "2.0 Ghz"
$myObject3 | Add-Member -type NoteProperty -name Memory -Value "2.5 GB"

Now we have three different objects,  so let’s create an empty array to place them in.

$myArray = @()

Okay, so now is simply adding the objects into the array.  You can use the += operator to do it.

$myArray += $myObject
$myArray += $myobject2, $myObject3

Notice that you can add more than one object to an array at once, if you like. 

Now that this is complete we have a list of all our custom objects.  This can be displayed nicely on the screen or even sent to out-gridview to give you a nice Excel-like view which can be searched, sorted, and filtered.  You can also use the array in a ForEach statement to run code against.  Keep in mind that you can also create the array of objects by adding one at a time in any given loop.  This is exactly how I create the server lists for the companies I work for.  It’s also worth stating that the “Add-Member” commandlet must have the value given, but you can simply give and empty string “” if you want to define it later.

> $myArray

Name         Manufacturer    ProcessorSpeed   Memory
----         ------------    --------------   ------
Ryan_PC      Dell            3 Ghz            6 GB
Doug_PC      Dell            2.6 Ghz          4 GB
Julie_PC     Compaq          2.0 Ghz          2.5 GB

> $myArray | Select-Object name

Name
----
Ryan_PC
Doug_PC
Julie_PC

Enjoy!

  11 Responses to “Creating an Array of Custom Objects in Powershell”

  1. when I output my array, with 2 entries in it i get

    System.ObjectSystem.Object

    while I have my code in a loop, i don’t see the difference
    code:

    $roguesize = $null
    $roguesize = @()

    foreach ($item in $roguefldr)
    {

    $foldersize = ((Get-ChildItem “c:\$item” -Recurse | Measure-Object -Property Length -Sum -ErrorAction silentlycontinue).Sum / 1GB)
    #since we don’t care about empty folders, ignore them
    if (($foldersize * 1073741824) -lt 1MB)
    {
    $fileobject = $null
    $fileobject = New-Object System.Object
    $fileobject | Add-Member -type NoteProperty -Name Name -Value $item
    $fileobject | Add-Member -type NoteProperty -Name Size -Value $foldersize
    $roguesize += $fileobject
    }
    }
    $roguesize

  2. Looking all over the Internet and the only thing my code needed was that “+=” to add objects to the array… Thanks mate, you saved my day (or at least, some of it).

  3. This simplified information, saved lot of hours and pain in learning Power Shell (custom objects).

  4. I have created an array of objects similar to the example above. However, no I need to be able to update the one of the data fields within a specific object but I can’t figure out how to access it.
    Any ideas would be greatly appreciated.

    My (flawed) logic was something like this. I know it’s not working but hopefully it may give someone an inspiration for a better method.

    ($arrofObjects.Alias | select-object | where HostName -like $_.’name’) = $newAlias

    I’m already able to isolate the object in question by the where statement. I just can’t figure out how to add new data to that existing object.

    Any suggestions?

    Thanks,
    DBG

    • Once you have the object you can write attributes like $MyObject.AttributeName = “MyValue” and retrieve them with $MyObject.AttributeName

  5. Bless your soul. saved new to powershell and this helped me out very much.

  6. This is an essential read for those new to powershell. Very well laid out.

  7. There is another quick way to do the same thing:
    $obj= “” | select Name, Manufacturer , ProcessorSpeed , Memory

  8. I need types other than “notepropertly”. I need an array, or list, to be one of the properties…

  9. Thank you very much. This is a very easy way to organize a LOT of information. I did use it to get information about computers from AD:

    Foreach ($result in $results) {
    $Server = $result.GetDirectoryEntry()
    [string]$Server1 = $Server.cn #server name
    [string]$Server2 = $Server.description.Value # Server description
    $Server3 = $null ; $Server3 = $Server.Parent -split(“,”)
    $Server3 = $Server3[0] -replace(“LDAP://OU=”,””) #server paren ou
    [string]$Server4 = $Server.operatingSystem
    [string]$Server5 = $Server.operatingSystemVersion
    [string]$Server6 = $Server.operatingSystemServicePack
    [string]$Server7 = $Server.dNSHostName

    $obj = $null
    $obj = New-Object System.Object
    $obj | Add-Member -type NoteProperty -Name ComputerName -Value $Server1
    $obj | Add-Member -type NoteProperty -Name Description -Value $Server2
    $obj | Add-Member -type NoteProperty -Name ParentOU -Value $Server3
    $obj | Add-Member -type NoteProperty -Name OS -Value $Server4
    $obj | Add-Member -type NoteProperty -Name OSVersion -Value $Server5
    $obj | Add-Member -type NoteProperty -Name OSServicePack -Value $Server6
    $obj | Add-Member -type NoteProperty -Name DNSName -Value $Server7

    $ServerArr += $obj
    $i++

    }

 Leave a Reply

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">

(required)

(required)

This site uses Akismet to reduce spam. Learn how your comment data is processed.