如果您通过索引比较两个文件,这意味着,比较file1 与 on file2和index 0
儿子我个人根本不会使用,因为它非常慢:index 0
Compare-Object
$arr1 = 'orange','strawberry','orange'
$arr2 = 'banaple','cherry','orange','banana'
# Note: I'm placing those 2 arrays for demonstration purposes only.
# $arr1 and $arr2 should be changed to:
# $arr1 = Get-Content .\txt1.txt
# $arr2 = Get-Content .\txt2.txt
$totalCount = ($arr1.Count, $arr2.Count | Measure-Object -Maximum).Maximum
$arr3 = for($i=0;$i -lt $totalCount;$i++)
{
$status = 'NO CHANGE'
if($arr1[$i] -ne $arr2[$i])
{
$status = 'UPDATED'
}
[pscustomobject]@{
Before = $arr1[$i]
After = $arr2[$i]
Status = $status
}
}
Before After Status
------ ----- ------
orange banaple UPDATED
strawberry cherry UPDATED
orange orange NO CHANGE
banana UPDATED
- 如果要导出
$arr3
,我建议您使用 CSV 作为导出格式:
$arr3 | Export-Csv absolultepath\to\file3.csv -NoTypeInformation
$arr3 | Out-File absolultepath\to\file3.txt
相同的逻辑,但作为一个函数:
function Compare-Files {
[cmdletbinding()]
param(
[parameter(mandatory)]
[ValidateScript({Test-Path $_ -PathType Leaf})]
[System.IO.FileInfo]$BeforeFile,
[parameter(mandatory)]
[ValidateScript({Test-Path $_ -PathType Leaf})]
[System.IO.FileInfo]$AfterFile
)
$file1 = Get-Content $BeforeFile
$file2 = Get-Content $AfterFile
$totalCount = ($file1.Count, $file2.Count | Measure-Object -Maximum).Maximum
for($i=0;$i -lt $totalCount;$i++)
{
$status = 'NO CHANGE'
if($file1[$i] -ne $file2[$i])
{
$status = 'UPDATED'
}
[pscustomobject]@{
Before = $file1[$i]
After = $file2[$i]
Status = $status
}
}
}
演示:
PS /> Compare-Files -BeforeFile .\file1.txt -AfterFile .\file2.txt
Before After Status
------ ----- ------
orange banaple UPDATED
strawberry cherry UPDATED
orange orange NO CHANGE
banana UPDATED
PS /> Compare-Files -BeforeFile .\file1.txt -AfterFile .\file2.txt | Export-Csv ...