Powershell匹配属性,然后有选择地组合对象以创建第三个对象 [英] Powershell match properties and then selectively combine objects to create a third
问题描述
我对此有一个解决方案,但我认为这并不是最好的方法,因为它永远存在,因此我正在寻找一种更快/更好/更智能的方法.
I have a solution for this but I believe it is not the best method as it takes forever so I am looking for a faster/better/smarter way.
我从.csv文件中提取了多个pscustomObject对象.每个对象至少具有一个公共属性.一个相对较小(对象中约200-300个项目/行),而另一个则相当大(约60,000-100,000个项目).一个的内容可能匹配另一个的内容,也可能不匹配.
I have multiple pscustomObject objects pulled from .csv files. Each object has at least one common property. One is relatively small (around 200-300 items/lines in the object) but the other is sizable (around 60,000-100,000 items). The contents of one may or may not match the contents of the other.
我需要找到两个对象在特定属性上匹配的位置,然后将每个对象的属性组合为一个具有全部或大多数属性的对象.
I need to find where the two objects match on a specific property and then combine the properties of each object into one object with all or most properties.
该代码的示例片段(虽然不完全,但是应该可以正常工作-请参见图像以获取示例数据): 数据表
An example snippet of the code (not exact but for this it should work - see the image for the sample data): DataTables
Write-Verbose "Pulling basic Fruit data together"
$Purchase = import-csv "C:\Purchase.csv"
$Selling = import-csv "C:\Selling.csv"
Write-Verbose "Combining Fruit names and removing duplicates"
$Fruits = $Purchase.Fruit
$Fruits += $Selling.Fruit
$Fruits = $Fruits | Sort-Object -Unique
$compareData = @()
Foreach ($Fruit in $Fruits) {
$IndResults = @()
$IndResults = [pscustomobject]@{
#Adding Purchase and Selling data
Farmer = $Purchase.Where({$PSItem.Fruit -eq $Fruit}).Farmer
Region = $Purchase.Where({$PSItem.Fruit -eq $Fruit}).Region
Water = $Purchase.Where({$PSItem.Fruit -eq $Fruit}).Water
Market = $Selling.Where({$PSItem.Fruit -eq $Fruit}).Market
Cost = $Selling.Where({$PSItem.Fruit -eq $Fruit}).Cost
Tax = $Selling.Where({$PSItem.Fruit -eq $Fruit}).Tax
}
Write-Verbose "Loading Individual results into response"
$CompareData += $IndResults
}
Write-Output $CompareData
我认为问题出在以下方面:
I believe the issue is in lines like these:
Farmer = $Purchase.Where({$PSItem.Fruit -eq $Fruit}).Farmer
如果我理解这一点,则它每次通过此行时都在遍历$ Purchase对象.我正在寻找一种加快整个过程的方法,而不是让每次匹配尝试都遍历整个对象.
If I understand this it is looking through the $Purchase object each time it goes through this line. I am looking for a way to speed that whole process up instead of having it look through the entire object for each match attempt.
推荐答案
使用此 Join-Object
:
Using this Join-Object
:
$Purchase | Join $Selling -On Fruit | Format-Table
结果(使用Simon Catlin的数据):
Result (using Simon Catlin's data):
Fruit Farmer Region Water Market Cost Tax
----- ------ ------ ----- ------ ---- ---
Apple Adam Alabama 1 MarketA 10 0.1
Cherry Charlie Cincinnati 2 MarketC 20 0.2
Damson Daniel Derby 3 MarketD 30 0.3
Elderberry Emma Eastbourne 4 MarketE 40 0.4
Fig Freda Florida 5 MarketF 50 0.5
这篇关于Powershell匹配属性,然后有选择地组合对象以创建第三个对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!