我想比较两个csv文件并创建具有差异的第三个csv文件。
第一个csv文件是这样的
Name PowerState
---- ----------
vm1 VM deallocated
vm2 VM deallocated
vm3 No data
vm4 No data
vm5 VM deallocated
第二个csv:
Name PowerState
---- ----------
vm1 VM deallocated
vm2 VM running
vm3 VM running
vm4 VM deallocated
vm5 VM deallocated
我想与powershell进行比较,所以这是我的代码:
$csv1 = Import-Csv -Path c:\temp\csv1.csv
$csv2 = Import-Csv -Path c:\temp\csv2.csv
$output = @()
forEach ($Row in $csv1) {
$powerstate = "ShutdownScriptState: " + $Row.PowerState + " | Now: " + $result.PowerState
$output += New-object PSObject -property @{
Name = $Row.Name
PowerState = $powerstate
}
}
$result = $csv2 | where {$_.csv2 -ne $name.PowerState}
$output | select-object Name, PowerState | Export-Csv -Path C:\temp\final.csv -NoTypeInformation -delimiter ","
但是在输出final.csv时不完整:
Name PowerState
---- ----------
adfs ShutdownScriptState: VM deallocated | Now:
adfs40 ShutdownScriptState: VM deallocated | Now:
ardal ShutdownScriptState: No data | Now:
backupDPM ShutdownScriptState: No data | Now:
BizTalk2016 ShutdownScriptState: VM deallocated | Now:
现在缺少:($ result.PowerState)
我不明白。
答案 0 :(得分:1)
我将使用Compare-Object
进行比较,然后在Name上分组以并排获得差异。
## Q:\Test\2018\07\19\SO_51428482.ps1
$csv1 = Import-Csv -Path 'c:\temp\csv1.csv'
$csv2 = Import-Csv -Path 'c:\temp\csv2.csv'
$Result = Compare-Object $csv1 $csv2 -Property Name,PowerState |
Group-Object Name | ForEach-Object{
[PSCustomObject]@{
Name = $_.Name
Powerstate_1st = ($_.Group | Where SideIndicator -eq "<=").Powerstate
Powerstate_Now = ($_.Group | Where SideIndicator -eq "=>").Powerstate
}
}
$Result
$Result | Export-Csv '.\final.csv' -NoTypeInformation
样本输出
Name Powerstate_1st Powerstate_Now
---- -------------- --------------
vm2 VM deallocated VM running
vm3 No data VM running
vm4 No data VM deallocated
要准确地将您的所需输出更改为{strong> ,
[PSCustomObject]
[PSCustomObject]@{
Name = $_.Name
Powerstate = ("ShutdownScriptState: {0} | {1}" -f `
($_.Group | Where SideIndicator -eq "<=").Powerstate,
($_.Group | Where SideIndicator -eq "=>").Powerstate)
}
答案 1 :(得分:0)
在设置变量之前,您尝试从其他范围访问$Result
变量。
移动
$result = $csv2 | where {$_.csv2 -ne $name.PowerState}
在ForEach循环中
之前$powerstate = "ShutdownScriptState: " + $Row.PowerState + " | Now: " + $result.PowerState
您还需要将该行更改为:
$result = $csv2 | where {$_.Name -eq $Row.Name}
答案 2 :(得分:0)
您无序访问变量,无法正确比较。此代码段应该可以简洁地解决您的问题:
$csv1 = Import-Csv -Path c:\temp\csv1.csv
$csv2 = Import-Csv -Path c:\temp\csv2.csv
$output = foreach ($row in $csv1) {
$compare = $csv2 | Where-Object Name -eq $row.Name
if ($row.PowerState -ne $compare.PowerState) {
[pscustomobject]@{
Name = $row.Name
PowerState = "ShutdownScriptState: $($row.PowerState) | Now: $($compare.PowerState)"
}
}
}
$output | Export-Csv -Path C:\temp\final.csv -NoTypeInformation