2

问题

我有两个 CSV 文件,文件 A 和文件 B。这两个文件都包含相同的标题。
这些文件包含有关报价和订单的信息。

首先在上午 10:00 创建文件 A。文件 B 于上午 11:00 创建。那是状态列值从“报价”更新为“订单”的时候,也许还有其他一些细节。

我使用Compare-ObjectExport-Csv结合将差异导出到新的 CSV 文件,但仅应导出最新(最新)信息。
问题是:Compare-Object正确检测到特定行已更改,但不是使用文件 B 中的数据,而是使用文件 A(旧版本)中的数据。

示例(文件内容)

我以粗体突出显示了已更改的字段。

文件 A

“客户名称”、“地址”、“邮政编码”、“城市”、“参考编号”、“客户编号”、“状态代码”、“交货周”、“工作描述”、“状态”、“订单参考”、“顾问”  
"Example Customer","Example Address 1","9999 EX","EXAMPLE CITY","217098","8629",**"Quote"**,**""**,"Example Product","示例状态","私人","示例顾问"

文件 B

“客户名称”、“地址”、“邮政编码”、“城市”、“参考编号”、“客户编号”、“状态代码”、“交货周”、“工作描述”、“状态”、“订单参考”、“顾问”  
"Example Customer","Example Address 1","9999 EX","EXAMPLE CITY","217098","8629",**"Order"**,**"Call-off"**,"Example Product ","示例状态","私人","示例顾问"

脚本

好的,那里有很多台词。我将分享我认为问题应该存在的地方。

$timestamp = (get-date -UFormat "%A %d-%m-%Y %R" | ForEach-Object { $_ -replace ":", "-" })
$prefix="Export-"
$exportlocation = "C:\Users\username\Desktop\UTF8-format\" 
$ExportChangesFolder = "C:\Users\username\Desktop\Changes\"

$PreviousCSV = Import-Csv $PreviousFile -Header "CustomerName","Address","Postalcode","City","ReferenceNumber","CustomerNumber","Statuscode","DeliveryWeek","WorkDescription","Status","OrderReference","Advisor"
$NewCSV = Import-Csv $exportlocation$prefix$timestamp".csv" -Header "CustomerName","Address","Postalcode","City","ReferenceNumber","CustomerNumber","Statuscode","DeliveryWeek","WorkDescription","Status","OrderReference","Advisor"

$propsToCompare = $PreviousCSV[0].psobject.properties.name
Compare-Object -ReferenceObject $PreviousCSV -DifferenceObject $NewCSV -Property $propsToCompare -PassThru | select $propsToCompare | sort -Unique -Property "ReferenceNumber" | Select-Object * -ExcludeProperty SideIndicator | Export-Csv $ExportChangesFolder$prefix$timestamp".csv" -NoTypeInformation 

通常,所有文件名都会自动填充,因为这是使用 Windows 任务计划程序的重复任务设置。在故障排除期间,我手动填写了声明变量的文件名。每次我手动运行它时,它都可以正常工作!

4

1 回答 1

2

我认为您可能缺少的是SideIndicator. 您应该能够选择SideIndicators您想要的列表,其中“ <=”是仅存在于左侧 csv 中的事物,而“ =>”是仅存在于右侧的事物。

看起来您还指定了标头,然后从 csv 中获取标头,但您提到它们具有相同的标头?

Get-Date运行时以现有文件为目标Import-Csv也有点令人困惑,但我猜在导入和Get-Date运行之前构建这个 csv 的脚本还有更多内容。

这是我正在做的事情:

$timestamp = ((get-date -UFormat "%A %d-%m-%Y %R") -replace ":", "-")
$prefix="Export-"
$exportLocation = "C:\Users\username\Desktop\UTF8-format\" 
$exportChangesFolder = "C:\Users\username\Desktop\Changes\"

$headers = $previousCSV[0].psobject.properties.name

$previousCSV = Import-Csv $previousFile
$newCSV = Import-Csv $exportLocation$prefix$timestamp".csv"

$compareParams = @{
    ReferenceObject  = $previousCSV
    DifferenceObject = $newCSV
    Property         = $headers
    PassThru         = $true
}

Compare-Object @compareParams |
    Where-Object {$_.SideIndicator -eq "=>"} |
    Select-Object $headers | 
    Sort-Object -Unique -Property "ReferenceNumber" | 
    Select-Object * -ExcludeProperty SideIndicator |
    Export-Csv $exportChangesFolder$prefix$timestamp".csv" -NoTypeInformation
于 2021-01-10T00:21:53.247 回答