?
Solved

Powershell Enumerate memebers of a PSObject

Posted on 2012-03-22
8
Medium Priority
?
2,844 Views
Last Modified: 2012-03-29
Hi,

I am trying to work out how to write a powershell function that can enumerate all members of a PSObject and print the Member name and its value.

So if an object has 3 properties then I might see an output like the following:

Employee_Name : Fred
Employee_Age  : 18
Employee_Sex  : Male

So I am trying to write really a generic function that can handle any PSOBject (or other powershell object) and work it out.

In this simple example I have provided some code.

I know C# Reflection and was wondering how powershell would do it.

So in the example below in fnTest I would like to have something like:

function fnTest($data)
{
         foreach ($item in $data)
                  {
                         write-host $item.Label:  $item.Value
                   }
}

Thanks,

Ward.

function fnTest($data)
{
	# Here is want to seperate the Item Name and its value
}
		

$employee_list = @();		
$employee1 = New-Object PSObject
$employee1 | Add-Member Noteproperty Employee_Name -Value "Fred"
$employee1 | Add-Member Noteproperty Employee_Age -Value 18
$employee1 | Add-Member Noteproperty Employee_Sex -Value "Male"
$employee_list += $employee1
$employee2 = New-Object PSObject
$employee2 | Add-Member Noteproperty Employee_Name -Value "John"
$employee2 | Add-Member Noteproperty Employee_Age -Value 22
$employee2 | Add-Member Noteproperty Employee_Sex -Value "Male"
$employee_list += $employee2
$employee3 = New-Object PSObject
$employee3 | Add-Member Noteproperty Employee_Name -Value "Jane"
$employee3 | Add-Member Noteproperty Employee_Age -Value 32
$employee3 | Add-Member Noteproperty Employee_Sex -Value "Female"
$employee_list += $employee3

foreach ($employee in $employee_list)
{
    fnTest $employee  # <-- Function to enumerate object properties.
}

Open in new window

0
Comment
Question by:whorsfall
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 3
  • 2
  • 2
  • +1
8 Comments
 
LVL 11

Expert Comment

by:Joe Klimis
ID: 37756355
Hi you are doing well
you example is almost correct

$employee_list = @();		
$employee1 = New-Object PSObject
$employee1 | Add-Member Noteproperty Name -Value "Fred"
$employee1 | Add-Member Noteproperty Age -Value 18
$employee1 | Add-Member Noteproperty Sex -Value "Male"
$employee_list += $employee1
$employee2 = New-Object PSObject
$employee2 | Add-Member Noteproperty Name -Value "John"
$employee2 | Add-Member Noteproperty Age -Value 22
$employee2 | Add-Member Noteproperty Sex -Value "Male"
$employee_list += $employee2
$employee3 = New-Object PSObject
$employee3 | Add-Member Noteproperty Name -Value "Jane"
$employee3 | Add-Member Noteproperty Age -Value 32
$employee3 | Add-Member Noteproperty Sex -Value "Female"
$employee_list += $employee3

foreach ($employee in $employee_list)
{
    write-host "name : " , $employee.Name , "          Age: " , $employee.age , "           Sex: " , $Employee.sex

}
     

Open in new window



I hope this helps
joe
0
 

Author Comment

by:whorsfall
ID: 37756466
Hi,

Thanks for your response . I think u misunderstood my question a bit. I probably should of phrased it better. I wanted the fnTest function to be able to handle any type of PSObject passed to it and be able to enumerate the members.

So if I passed a different type of object with different members eg say "car_type" and "car_color" it can enumerate the $data variable within the fnTest function.

So fnTest can handle any type of object passed to it.

Sorry for the confusion

Ward
0
 
LVL 11

Expert Comment

by:Joe Klimis
ID: 37757679
There may better ways

but this work  for your example

use it like this

detailobject $employee_list

or
detailobject (get-process)


function detailObject($object)
{
$Properties = $object | gm -type Property,noteproperty
$Pcount = $properties.count
$counter = 0
While ( $counter -lt $pcount)
{ $name = ($properties[$counter].name) 
  $value = $object[$counter].$name
  Write-host "name : $name      Value:   $Value"
$counter++
}
}	 
	 

Open in new window

0
Linux Academy Android App Now Supports Chromecast

We have some fantastic news for our Android fans. We’re so excited to announce that the Linux Academy Android app is now available with Chromecast support. That’s right – simply download the latest update of the Linux Academy App and start casting your favorite course videos!

 
LVL 70

Expert Comment

by:Qlemo
ID: 37757900
Any reason you do not just use format-list *  ?
0
 
LVL 17

Expert Comment

by:Learnctx
ID: 37762231
Yeah I don't know why you wouldn't just use Select-Object * or Format-List *. These will both achieve what you want. If you did want a function to do it though, I guess you would have a reason...
Function fnTest($data)
{
    $arrProperties = $data | GM -MemberType Properties | Select -ExpandProperty Name
    Foreach ($property in $arrProperties)
    {
        Write-Host "$($property): $($data.$property)"
    }
}

Open in new window

But pretty much the output will be the same as just doing a format-list.
0
 

Author Comment

by:whorsfall
ID: 37762260
Hi,

Thanks for your answers. The reason why I am not using the standard methods is I posted this a more simple example.

What I wanted to do in the fnTest() function later exapand it so it can automate excel using COM.

So the first row would output the columns heading then below that I would put the members each data item into to each cell.

So the first row would be headings, the next row would be employee1 and the next row
employee2 and so on.

So in the modified version I might pass the variable $employee_list.

The excel com objects need me to fill the values cell by cell.

So I could not work out how to break up each item one by one.

However if there is a better way please let me know.

Thanks,

Ward.

e.g:

$excel = New-Object -ComObject Excel.Application
$excel.Visible = $true
$workbook1 = $excel.Workbooks.Add()

# write into cell B5 (column 2, line 5):
$workbook1.ActiveSheet.Cells.Item(5,2)= "I can write directly to cells!"

# read cell content
$content = $workbook1.ActiveSheet.Cells.Item(5,2).Text
"Cell B5 content: $content"
</code>
0
 
LVL 70

Accepted Solution

by:
Qlemo earned 2000 total points
ID: 37762577
Something like this?
set-StrictMode -Version latest

function Obj2XLS ([PSobject] $data)
{
  $excel = New-Object -ComObject excel.application
  $excel.visible=$true
  $wb = $excel.Workbooks.Add()            # empty, unnamed workbook

  #   Delete all but one work sheet
  $excel.DisplayAlerts = $false
  for ($i = $wb.Worksheets.Count; $i -ge 2; --$i) {$wb.Worksheets.Item($i).Delete()}
  $excel.DisplayAlerts = $true
  $ws = $wb.Worksheets.Item(1)

  $arrProperties = $data | gm -MemberType Properties 
  
  $row = 1
  $col = 1
  $arrProperties | % {
    $ws.Cells.Item($row, $col).value2 = $_.Name
    $ws.Cells.Item($row, $col++).Font.Bold = $true
  }
  $data | % {
    $row++
    $col = 1
    foreach ($prop in $arrProperties) {
      $ws.Cells.Item($row, $col).value2 = $_.$($prop.Name)
      $col++
    }
  }
  $ws.usedRange.EntireColumn.AutoFit() | Out-Null
  # $wb.SaveAs("YourFileNameHere")
  # $excel.Quit()
}

# --------------------------

$employee_list = @();		
$employee = New-Object PSObject
$employee | Add-Member Noteproperty Name -Value "Fred"
$employee | Add-Member Noteproperty Age -Value 18
$employee | Add-Member Noteproperty Sex -Value "Male"
$employee_list += $employee | select *
$employee.Name = "John"
$employee.Age  = 22
$employee.Sex  = "Male"
$employee_list += $employee | select *
$employee.Name = "Jane"
$employee.Age  = 32
$employee.Sex  = "Female"
$employee_list += $employee | select *


obj2XLS $employee_list

Open in new window

0
 

Author Closing Comment

by:whorsfall
ID: 37785789
Awsome - thanks :)
0

Featured Post

Monthly Recap

May was a big month for new releases from Linux Academy! Take a look at what our team built recently in our blog. You can access the newest releases from our blog.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

My attempt to use PowerShell and other great resources found online to simplify the deployment of Office 365 ProPlus client components to any workstation that needs it, regardless of existing Office components that may be needing attention.
There are times when we need to generate a report on the inbox rules, where users have set up forwarding externally in their mailbox. In this article, I will be sharing a script I wrote to generate the report in CSV format.
The viewer will learn how to look for a specific file type in a local or remote server directory using PHP.
The viewer will learn how to create and use a small PHP class to apply a watermark to an image. This video shows the viewer the setup for the PHP watermark as well as important coding language. Continue to Part 2 to learn the core code used in creat…
Suggested Courses

762 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question