我有两个自定义对象数组-$ deploy和$ directory。它们具有4个共同的属性和1个唯一的属性。我需要找到两个数组的4个公共属性相同的成员,但是我还需要跟踪匹配项的2个唯一属性。
在具有定义相同属性的两个数组上使用比较对象-passthru和-includeequal差不多,但是只给我第一个(引用)对象及其唯一属性,而不是差异对象上的唯一属性。
所以我不能简单地比较两个数组并得到我所需要的。我要么需要做一个嵌套循环,要么破解/找到某种“设置交集”功能。我将只处理每个数组的几十个成员,因此我不太担心性能。
您将采用哪种方法?对于下面的简单示例,我希望同时跟踪环境名称和部署目录以查找所有匹配项。
$deploy
GameBuildVersion : 68858.zip
OnlineVersion : 70793.zip
ContentVersion : 68858.69165-1.zip
ContentBuildVersion : 69165-1.zip
environmentname : Staging35
$directory
GameBuildVersion : 68858.zip
OnlineVersion : 70793.zip
ContentVersion : 68858.69165-1.zip
ContentBuildVersion : 69165-1.zip
deploymentDirectory : C:\deployer\script\deploy-AB
答案 0 :(得分:1)
这可能不是最快的方法,但这是我想出的:
# create a string array storing the combined properties of the 4 common $deploy objects.
# convert these strings to lowercase, because later on we use IndexOf and that is case sensitive.
$commons = @()
$deploy | ForEach-Object {
$commons += $("{0},{1},{2},{3}" -f $_.GameBuildVersion, $_.OnlineVersion, $_.ContentVersion, $_.ContentBuildVersion).ToLower()
}
# create an array to store the objects both arrays have in common, combined with their unique properties
$result = @()
$directory | ForEach-Object {
$props = $("{0},{1},{2},{3}" -f $_.GameBuildVersion, $_.OnlineVersion, $_.ContentVersion, $_.ContentBuildVersion).ToLower()
$index = $commons.IndexOf($props)
if ($index -ge 0) {
$result += [PSCustomObject]@{
GameBuildVersion = $_.GameBuildVersion
OnlineVersion = $_.OnlineVersion
ContentVersion = $_.ContentVersion
ContentBuildVersion = $_.ContentBuildVersion
deploymentDirectory = $_.deploymentDirectory
environmentname = $deploy[$index].environmentname
}
}
}
# show the result (or export it to CSV or whatever)
$result
使用您提供的示例,结果将是:
GameBuildVersion : 68858.zip
OnlineVersion : 70793.zip
ContentVersion : 68858.69165-1.zip
ContentBuildVersion : 69165-1.zip
deploymentDirectory : C:\deployer\script\deploy-AB
environmentname : Staging35