Home > Blockchain >  How to get the name of a PsCustomObject?
How to get the name of a PsCustomObject?

Time:07-12

I have a Powershell-script which includes a lot of PsCustomObjects like this (names do not have a specific pattern):

$myObject1 = [PSCustomObject]@{
    Name     = 'Kevin'
    State    = 'Texas'
}

$myObject2 = [PSCustomObject]@{
    Name     = 'Peter'
    Lastname = 'Fonda'
    State    = 'Florida'
}

Now I need to convert this programmatically into the following object-format to have a global hashtable:

$result = @{
    'myObject1.Name'     = 'Kevin'
    'myObject1.State'    = 'Texas'
    'myObject2.Name'     = 'Peter'
    'myObject2.Lastname' = 'Fonda'
    'myObject2.Sate'     = 'Florida'
}

For this task I need a loop in which I can either read the name of each PsCustomOject or I need to specify the names of all object as a string-array and lookup the object-properties with the matching name.

The loop-constructor could look something like this:

$result = @{}
foreach($name in @('myObject1','myObject2')) {
    $obj = myMissingFunction1 $name
    foreach($p in $obj.PsObject.Properties) {
        $result["$name.$($p.Name)"] = $p.Value
    }
}

or this

$result = @{}
foreach($obj in @($myObject1, $myObject2)) {
    $name = myMissingFunction2 $obj
    foreach($p in $obj.PsObject.Properties) {
        $result["$name.$($p.Name)"] = $p.Value
    }
}

Unfortunately I cannot bring any of the two approaches to life. Can someone please help?

CodePudding user response:

Here is how you could do it .

$Result = [Ordered]@{}
$index = 0
Foreach ($obj in $ArrayOfObject) {
    foreach ($prop in ($obj | Get-Member -MemberType NoteProperty).Name) {
        $Result."SomeObject$Index.$Prop" = $obj.$prop
    }
    $index  = 1
   
}

Result

Name                           Value
----                           -----
SomeObject0.Name               Kevin
SomeObject0.State              Texas
SomeObject1.Lastname           Fonda
SomeObject1.Name               Peter
SomeObject1.State              Florida

Dataset used for this example

$ArrayOfObject = @(
    [PSCustomObject]@{
        Name  = 'Kevin'
        State = 'Texas'
    }
    [PSCustomObject]@{
        Name     = 'Peter'
        Lastname = 'Fonda'
        State    = 'Florida'
    }
)

CodePudding user response:

Solved it finally. I completely forgot the "Get-Variable" function:

$result = @{}
foreach($name in @('myObject1','myObject2')) {
    $obj = (Get-Variable $name).Value
    foreach($p in $obj.PsObject.Properties) {
        $result["$name.$($p.Name)"] = $p.Value
    }
}
  • Related