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?
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"
}
This should get you what you need:
$NetworkInfo | get-member -type NoteProperty | foreach-object {
$name=$_.Name ;
$value=$NetworkInfo."$($_.Name)"
write-host "$name = $value"
}
Try:
ForEach ($noteProperty in $NetworkInfo.PSObject.Properties)
{
Write-Host $noteProperty.Name
Write-Host $noteProperty.Value
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With