Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Looping through each NoteProperty in a custom object

Tags:

powershell

I'm creating a PSObject in Powershell like this:

$NetworkInfo = New-Object PSObject
$NetworkInfo | Add-Member -type NoteProperty -Name IPAddress -Value "10.10.8.11"
$NetworkInfo | Add-Member -type NoteProperty -Name SubnetMask -Value "255.255.255.0"
$NetworkInfo | Add-Member -type NoteProperty -Name Gateway -Value "10.10.8.254"
$NetworkInfo | Add-Member -type NoteProperty -Name Network -Value "10.10.8.0"
$NetworkInfo | Add-Member -type NoteProperty -Name DNS1 -Value "10.10.10.200"
$NetworkInfo | Add-Member -type NoteProperty -Name DNS2 -Value "10.10.10.201"

$NetworkInfo

I want to do a specific action for each NoteProperty in this PSObject, but I'm not sure how to go about doing that. For example (even though I know it's the wrong way to do it) this code:

  ForEach ($noteProperty in $NetworkInfo) {
    Write-Host $noteProperty
  }

Only outputs the entire object as an array:

@{IPAddress=10.10.8.11; SubnetMask=255.255.255.0; Gateway=10.10.8.254; Network=10.10.8.0; DNS1=10.10.10.200; DNS2=10.10.10.201}

EDIT: Each NoteProperty is of the variable type System.String - if that's pertinent.

Am I creating the object incorrectly, or do I just not understand how to go through the object?

like image 834
Medos Avatar asked Dec 24 '14 21:12

Medos


3 Answers

You can use Get-Member as mentioned by Mike; an alternative that keeps the order is to use the PSObject property that is present on all objects:

#View details for all properties on a specific object
$NetworkInfo.PSObject.Properties

#similar code to Mike's, working with name and value:
$NetworkInfo.PSObject.Properties | foreach-object {
    $name = $_.Name 
    $value = $_.value
    "$name = $value"
}
like image 120
Cookie Monster Avatar answered Nov 15 '22 11:11

Cookie Monster


This should get you what you need:

$NetworkInfo | get-member -type NoteProperty | foreach-object {
  $name=$_.Name ; 
  $value=$NetworkInfo."$($_.Name)"
  write-host "$name = $value"
}
like image 23
Mike Shepard Avatar answered Nov 15 '22 09:11

Mike Shepard


Try:

ForEach ($noteProperty in $NetworkInfo.PSObject.Properties)
{
   Write-Host $noteProperty.Name
   Write-Host $noteProperty.Value
}
like image 3
AGO Avatar answered Nov 15 '22 11:11

AGO