提问人:SuperZee 提问时间:7/14/2023 最后编辑:Mathias R. JessenSuperZee 更新时间:7/14/2023 访问量:48
使用 PowerShell 比较原始文件和最后两个文件
Comparing original file and last two files using PowerShell
问:
我有另一个脚本,每 4 小时将数据输出到 csv 文件中,并将文件创建为 .vdsinfo_$(Get-Date -Format "yyMMdd_hh-mm-ss").csv
我希望能够将创建的原始文件和最近创建的两个文件相互比较,以查看文件中是否有更改。
目前,这是我为脚本准备的,但它还没有完全存在,非常感谢一些帮助,以产生写入文件的输出。Changes.csv
我想比较文件名总是在变化的文件,因此脚本需要尽可能使用变量,而我可以看到这种工作的唯一方法是通过 get-date addhours-4。
$File = 'E:\TEMP\Changes.csv'
# Get File item
$file1 = Get-ChildItem -Path E:\TEMP\reports\vdsinfo_original.csv
# Get the specific date
$date1 = (Get-Date).AddHours(-8)
# Compare file modified date with specific date
$file2 = $file1.LastWriteTime -gt $date1
Compare-Object -ReferenceObject $file1 -DifferenceObject $file2 -CaseSensitive | Format-table InputObject, SideIndicator -Autosize | out-file $file -Width 200
Else {
Write-Host "File missing " -ForegroundColor White -BackgroundColor Red
}
任何帮助都会对我有所帮助,提前致谢
使用此当前脚本,它仅与两个文件进行比较,我想与文件夹位置中的原始文件和最后两个文件进行比较。
答:
0赞
Mathias R. Jessen
7/14/2023
#1
我希望能够将创建的原始文件和最近创建的两个文件相互比较,以查看文件中是否有更改。
这有点不清楚,但在下文中,我将假设您要生成 2 组更改:
- 原始文件和最新版本之间所有更改的完整集合
- 最新的一组更改 - 在倒数第二个版本和最新版本之间
我可以看到这种工作的唯一方法是通过获取日期 addhours-4。
这完全没有必要。文件名包含可排序的日期/时间戳,因此请按名称对文件进行排序,然后您可以简单地跳转到排序列表中的上一个文件并获取 4 小时前的数据:
# define output destinations
$outFilePaths = @{
All = 'E:\TEMP\AllChanges.csv'
Latest = 'E:\TEMP\LatestChanges.csv'
}
# find the original file
$originalFile = Get-Item -Path E:\TEMP\reports\vdsinfo_original.csv
# find all the subsequent versions of the file, make sure
# they're sorted by name, then store them in an array
$files = @(Get-ChildItem -Path E:\TEMP\reports -Filter vdsinfo_[0-9]*.csv |Sort-Object Name)
# make sure we've located at least one subsequent version - otherwise there's nothing to compare against!
if ($files.Count -gt 0) {
# let's start by comparing original with the latest version
#
# $files[-1] is going to evaluate to the _last_ item in the $files array
$allChanges = Compare-Object -ReferenceObject ($originalFile |Get-Content) -DifferenceObject ($files[-1] |Get-Content)
# output to a file
$allChanges |Format-table InputObject, SideIndicator -Autosize |Out-File $filePaths['All'] -Width 200
# repeat comparison between the two latest versions
$latestChanges = Compare-Object -ReferenceObject ($files[-2] |Get-Content) -DifferenceObject ($files[-1] |Get-Content)
# output to a file
$latestChanges |Format-table InputObject, SideIndicator -Autosize |Out-File $filePaths['Latest'] -Width 200
}
else {
Write-Host "Updated files are missing" -ForegroundColor White -BackgroundColor Red
}
评论