0

Hi I have n sum of objects for each Node like this:

NodeName                              : 11111
System.AreaId                         : 2375
System.AreaPath                       : Project
System.TeamProject                    : Project
System.NodeName                       : Project
System.AreaLevel1                     : Project

Every node can have different objects in it. How can I split them to an arrays/strings without specifying the object name so I can create foreach separate object loop?

Baequiraheal
  • 119
  • 1
  • 13
  • Can you edit your question displaying what would be the expected output ? – Santiago Squarzon May 23 '21 at 19:50
  • 3
    You can invoke `.psobject.Properties` on any object in PowerShell to get a collection of its public properties. – mklement0 May 23 '21 at 19:50
  • Thanks @mklement0 I didn't know that. This is what I wanted. Can you recommend me PowerShell readings for useful tricks like this one? – Baequiraheal May 23 '21 at 19:53
  • @Baequiraheal, I compiled a list of learning resource in [this answer](https://stackoverflow.com/a/48491292/45375) a while ago. Fundamentally, learning how to use PowerShell's help system efficiently and studying the conceptual `about_*` topics helps, though they don't tell the full story. There's also good information in the answers here on SO. – mklement0 May 23 '21 at 21:06
  • If this comes from a `Json` file consider to use the [`ConvertFrom-Json -AsHashTable`](https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.utility/convertfrom-json?view=powershell-7.1#parameters) parameter as it gives you an easier access to the keys. – iRon May 24 '21 at 07:43

1 Answers1

2

mklement0 beat me to what I was going to post. Since I have the code drafted already I will post it.

Like mklement0 said in comments, you can access object properties through use of .psobject.Properties. Below in the code I am using a switch statement to check if an object contains a specific property.

$objs = @(
[pscustomobject]@{
    AreaId      = 2375
    AreaPath    = ''
    TeamProject = 'Project2'
    NodeName    = ''
    AreaLevel1  = ''
},
[pscustomobject]@{
    AreaId      = 342
    AreaPath    = ''
    TeamProject = 'Project2'
    Color       = 'Red'
}

)

switch ($objs) {
    { $_.psobject.properties.name -contains 'Color' } {
        'Object contains Color property'
    }
    { $_.psobject.properties.name -contains 'NodeName' } {
        'Object contains NodeName property'
    }
    Default {}
}
Daniel
  • 4,792
  • 2
  • 7
  • 20