我在Powershell中创建了一个像这样的PSObject
:
$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
我想为这个PSObject中的每个NoteProperty做一个特定的动作,但是我不知道如何去做。例如(尽管我知道这是错误的方法)这段代码:
ForEach ($noteProperty in $NetworkInfo) {
Write-Host $noteProperty
}
仅将整个对象输出为数组:
@{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}
编辑:每个NoteProperty
是变量类型System.String
- 如果这是相关的。
我是否错误地创建了对象,或者我只是不明白如何浏览对象?
您可以使用Mike提到的Get-Member;保持顺序的替代方法是使用所有对象上存在的PSObject属性:
#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"
}
这应该可以满足您的需求:
$NetworkInfo | get-member -type NoteProperty | foreach-object {
$name=$_.Name ;
$value=$NetworkInfo."$($_.Name)"
write-host "$name = $value"
}
尝试:
ForEach ($noteProperty in $NetworkInfo.PSObject.Properties)
{
Write-Host $noteProperty.Name
Write-Host $noteProperty.Value
}