Create Custom PSObject PowerShell 2.0

powershell

Solution

I'm not sure I follow. Do you want an array of objects with your specified properties? Because your sample first creates an array, that you then overwrite into a single object. So you lost your array.

You can create the object using `new-object` and specify the properties with values as a hashtable in the `-Property` parameter. Like this:

$c = New-Object psobject -Property @{
    Name = "John"
    Gender = "Male"
    Age = 30
}

To make an array of them, you can use:

$myarray = @()

$myarray += New-Object psobject -Property @{
    Name = "John"
    Gender = "Male"
    Age = 30
}

If you have multiple tests that you run one by one, you can run the tests in a function that tests and creates a "resultobject", then you collect it:

$myresults = @()

function mytests($computer) {
    #Test connection
    $online = Test-Connection $computer

    #Get buildnumber
    $build = (Get-WmiObject win32_operatingsystem -ComputerName $computer).buildnumber

    #other tests

    #output results
    New-Object psobject -Property @{
        Online = $online
        WinBuild = $build
    }
}

$myresults += mytests -computer "mycomputername"

Problem

Is it possible to create a Custom Object (PSObject) and define its properties beforehand and later in the program execution, we keep adding array of values to the object. For e.g; ``` $c = @() $c = New-Object PSObject $c | Add-Member -type NoteProperty -name Name $c | Add-Member -type NoteProperty -name Gender $c | Add-Member -type NoteProperty -name Age $c | Add-Member -type NoteProperty -name Name -value "John" $c | Add-Member -type NoteProperty -name Gender -value "Male" $c | Add-Member -type NoteProperty -name Age -value "30" ``` Thanks in advance for any leads or advice.

Original source