我创建了一个对象作为客户导入的一部分。现在,每个客户对象都有一组动态属性,所有属性都具有前缀:“Cust”。 。我只需要遍历这些属性,然后首先获取属性的名称,然后获取值。
$customerOptions = $Customer | Select-Object -property "Cust.*"
答案 0 :(得分:1)
由于关于$Customer
是什么以及您想要使用什么的信息不多,我猜测$Customer
是单个对象而不是数组。要循环访问以Cust.
开头的属性,同时能够访问property-name和property-value,我会使用它。根据您的需求进行定制:
$Customer = [pscustomobject]@{ Name = "Object1"; "Cust.ID" = 1; "Cust.Car" = "Mercedes"}
$Customer.psobject.Properties | Where-Object { $_.Name -like 'Cust.*' } | ForEach-Object {
#Foreach property with a Cust. prefix
$PropertyName = $_.Name
$PropertyValue = $_.Value
Write-Host "$PropertyName = '$PropertyValue'"
}
输出:
Cust.ID = '1'
Cust.Car = 'Mercedes'
如果您正在输出一个数组,而您只获得了一些属性(第一个对象中可用的属性),如:
$Customer = @()
$Customer += [pscustomobject]@{ Name = "Object1"; "Cust.ID" = 1; "Cust.Car" = "Mercedes"}
$Customer += [pscustomobject]@{ Name = "Object2"; "Cust.ID" = 2; "Cust.Moped" = "Vespa"}
$Customer | Select-Object -Property "Cust.*"
Cust.ID Cust.Car
------- --------
1 Mercedes
2
然后,您需要创建cust.*
- 属性的完整列表,并在Select-Object
语句中使用该列表:
$AllCustProperties = $Customer | ForEach-Object { $_.psobject.Properties } | Where-Object { $_.Name -like 'Cust.*' } | Select-Object -ExpandProperty Name -Unique
$Customer | Select-Object -Property $AllCustProperties
Cust.ID Cust.Car Cust.Moped
------- -------- ----------
1 Mercedes
2 Vespa
答案 1 :(得分:0)
您可以通过隐藏的psobject
属性检查每个自定义对象的属性名称:
$Customer[0].psobject.Properties |Where-Object {$_.Name -like 'Cust.*'} |Select Name,Value
您还可以使用此技术枚举所有可能的属性名称并将其提供给Select-Object
$CustPropNames = $Customer |ForEach-Object {
$_.psobject.Properties |Where-Object {$_.Name -like 'Cust.*'} |Select-Object -Expand Name
} |Select-Object -Unique
$customerOptions = $Customer |Select-Object -Property $CustPropNames