我有一个如下所示的Powershell阵列:
TSMServer Cluster VM
--------- ------- --
HTS01 APP-P02 Server9839
HTS01 APP-P13 Server3221
HTS01 APP-P13 Server3230
HTS05 APP-P12 Server3182
HTS05 APP-P12 Server9829
GTS05 APP-P06 Server0057
GTS05 APP-P06 Server0421
GTS05 APP-P06 Server2426
GTS05 APP-P06 Server0286
GTS05 APP-P06 Server0302
GTS05 APP-P07 Server0312
GTS05 APP-P12 Server2845
GTS05 APP-P12 Server3135
HTS01 APP-P10 Server1052
HTS05 APP-P12 Server3155
HTS05 APP-P12 Server3185
HTS05 APP-P12 Server9830
...
我需要找到所有具有相同值的TSMserver和Cluster的VM。
我需要一个命令来检索(例如)这两个VM,因为它们共享相同的第一个值。
TSMServer Cluster VM
--------- ------- --
HTS01 APP-P13 Server3221
HTS01 APP-P13 Server3230
所以实际上我需要将数组中的每个对象与其他对象进行比较,以找到前两个属性的公共值。
非常感谢您!
答案 0 :(得分:0)
您可以使用Group-Object
cmdlet进行此操作,如下所示:
($ servers是此处包含对象数组的变量)
$servers | Group-Object -Property TSMServer, Cluster | Where-Object { $_.Count -gt 1 } | ForEach-Object {
$_.Group | Format-Table -AutoSize
}
对于给定的对象数组示例,运行以上命令将导致:
TSMServer Cluster VM
--------- ------- --
HTS01 APP-P13 Server3221
HTS01 APP-P13 Server3230
TSMServer Cluster VM
--------- ------- --
HTS05 APP-P12 Server3182
HTS05 APP-P12 Server9829
HTS05 APP-P12 Server3155
HTS05 APP-P12 Server3185
HTS05 APP-P12 Server9830
TSMServer Cluster VM
--------- ------- --
GTS05 APP-P06 Server0057
GTS05 APP-P06 Server0421
GTS05 APP-P06 Server2426
GTS05 APP-P06 Server0286
GTS05 APP-P06 Server0302
TSMServer Cluster VM
--------- ------- --
GTS05 APP-P12 Server2845
GTS05 APP-P12 Server3135
答案 1 :(得分:0)
使用组对象
$Servers = @"
TSMServer,Cluster,VM,
HTS01,APP-P02,Server9839
HTS01,APP-P13,Server3221
HTS01,APP-P13,Server3230
HTS05,APP-P12,Server3182
HTS05,APP-P12,Server9829
GTS05,APP-P06,Server0057
GTS05,APP-P06,Server0421
GTS05,APP-P06,Server2426
GTS05,APP-P06,Server0286
GTS05,APP-P06,Server0302
GTS05,APP-P07,Server0312
GTS05,APP-P12,Server2845
GTS05,APP-P12,Server3135
HTS01,APP-P10,Server1052
HTS05,APP-P12,Server3155
HTS05,APP-P12,Server3185
HTS05,APP-P12,Server9830
"@ | ConvertFrom-Csv
$Servers | Sort-Object TSMServer,Cluster | Group-Object TSMServer,Cluster|
ForEach-Object {
$TSMServer,$Cluster = $_.Name -split ', '
[PSCustomObject]@{
TSMServer = $TSMServer
Cluster = $Cluster
VMs =($_.Group.VM | Sort-Object) -Join ','
}
}
示例输出:
TSMServer Cluster VMs
--------- ------- ---
GTS05 APP-P06 Server0057,Server0286,Server0302,Server0421,Server2426
GTS05 APP-P07 Server0312
GTS05 APP-P12 Server2845,Server3135
HTS01 APP-P02 Server9839
HTS01 APP-P10 Server1052
HTS01 APP-P13 Server3221,Server3230
HTS05 APP-P12 Server3155,Server3182,Server3185,Server9829,Server9830