gpt4 book ai didi

PowerShell 比较对象生成更改报告文件

转载 作者:行者123 更新时间:2023-12-02 23:33:06 25 4
gpt4 key购买 nike

我查看了许多示例,并在生成变更报告方面取得了进展。但是,我被困在一个领域。这是场景...

File 1 CSV file sample data
ID,Name,Location,Gender
1,Peter,USA,Male
2,Paul,UK,Male
3,Mary,PI,Female

File 2 CSV file sample data (No ID column)
Name,Location,Gender
Peter,USA,Female
Paul,UK,Male
Mary,USA,Female
Tom,PI,Female
Barry,CAN,Male

文件2有变化和补充,即彼得变成了女性,玛丽搬到了美国,汤姆和巴里都是新人。更改报告输出文件包含更改内容。问题是,我不知道如何将文件 1 中 Peter 和 Mary 的 ID 获取到我的更改报告中。 ID 总是空的这是我的代码......(我希望有人能解释一下。提前致谢。)
$MyCSVFields = @('Name','Location','Gender')
$CompareResults = Compare-Object $RefObj $DffObj -Property $MyCSVFields -IncludeEqual
$NewOrChangedData = @()
Foreach($Row in $CompareResults)
{
if( $Row.SideIndicator -eq "=>" )
{
$TempObject = [pscustomobject][ordered] @{
ID = $Row.ID
Name = $Row.Name
Location = $Row.Location
Gender = $Row.Gender
#Sanity check "Compare Indicator" = $Row.SideIndicator
}
$NewOrChangedData += $TempObject
}
}

感谢 Theo 提供了如何使用 Where-Object 的理解。这是更新后的代码,它使初学者保持简单,并且仍然适用于我们。
Foreach($Row in $CompareResults)
{
if( $Row.SideIndicator -eq "=>" )
{
$myOrgID = $RefObj | Where-Object Name -eq $Row.Name
$TempObject = [pscustomobject][ordered] @{
ID = $myOrgID.ID
Name = $Row.Name
Location = $Row.Location
Gender = $Row.Gender
#Sanity check "Compare Indicator" = $Row.SideIndicator
}
$NewOrChangedData += $TempObject
}
}

最佳答案

我也一直在为 Compare-Object 苦苦挣扎,所以我希望有比这更好的答案:

$RefObj = @'
ID,Name,Location,Gender
1,Peter,USA,Male
2,Paul,UK,Male
3,Mary,PI,Female
'@ | ConvertFrom-Csv

$DffObj = @'
Name,Location,Gender
Peter,USA,Female
Paul,UK,Male
Mary,USA,Female
Tom,PI,Female
Barry,CAN,Male
'@ | ConvertFrom-Csv

$MyCSVFields = @('Name','Location','Gender')
$CompareResults = Compare-Object $RefObj $DffObj -Property $MyCSVFields -PassThru

$NewOrChangedData = $CompareResults | Where-Object { $_.SideIndicator -eq '=>' } | ForEach-Object {
$name = $_.Name
[PsCustomObject]@{
ID = ($RefObj | Where-Object { $_.Name -eq $name }).ID
Name = $name
Location = $_.Location
Gender = $_.Gender
#Sanity check "Compare Indicator" = $_.SideIndicator
}
}

$NewOrChangedData

结果:

ID 姓名 地点 性别
-- ---- -------- ------
1 彼得美国 女性
3 玛丽 美国 女
Tom PI 女
巴里 CAN 男

关于PowerShell 比较对象生成更改报告文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62457270/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com