Rajiv
Rajiv

Reputation: 685

Create Custom PSObject PowerShell 2.0

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.

Upvotes: 8

Views: 26925

Answers (2)

mcX
mcX

Reputation: 21

Yeah, so I know this is an old post but Don Jones did something like this:

$props = @{
    Name = "John"
    Gender = "Male"
    Age = 30
}

$c = New-Object PSObject -Property $props

You can run the following to see the Properties and Values the new Object:

c$ | Get-Member

I think that's what you're looking for.

Upvotes: 2

Frode F.
Frode F.

Reputation: 54881

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"

Upvotes: 18

Related Questions