使用 PowerShell 比较文件夹和内容 [英] Comparing folders and content with PowerShell

查看:66
本文介绍了使用 PowerShell 比较文件夹和内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个不同的 xml 文件文件夹.与另一个文件夹(文件夹 1)相比,一个文件夹(文件夹 2)包含更新的和新的 xml 文件.我需要知道文件夹 2 中的哪些文件与文件夹 1 相比是新的/更新的,并将它们复制到第三个文件夹(文件夹 3).在 PowerShell 中完成此操作的最佳方法是什么?

I have two different folders with xml files. One folder (folder2) contains updated and new xml files compared to the other (folder1). I need to know which files in folder2 are new/updated compared to folder1 and copy them to a third folder (folder3). What's the best way to accomplish this in PowerShell?

推荐答案

好吧,我不会为你编写整个代码(这有什么好玩的?)但我会让你开始.

OK, I'm not going to code the whole thing for you (what's the fun in that?) but I'll get you started.

首先,有两种方法可以进行内容比较.懒惰/大部分正确的方法,即比较文件的长度;以及更准确但更复杂的方法,即比较每个文件内容的哈希值.

First, there are two ways to do the content comparison. The lazy/mostly right way, which is comparing the length of the files; and the accurate but more involved way, which is comparing a hash of the contents of each file.

为了简单起见,让我们用简单的方法比较文件大小.

For simplicity sake, let's do the easy way and compare file size.

基本上,您需要两个代表源文件夹和目标文件夹的对象:

Basically, you want two objects that represent the source and target folders:

$Folder1 = Get-childitem "C:Folder1"
$Folder2 = Get-childitem  "C:Folder2"

然后你可以使用Compare-Object来查看哪些项目不同...

Then you can use Compare-Object to see which items are different...

Compare-Object $Folder1 $Folder2 -Property Name, Length

通过仅比较每个集合中文件对象的名称和长度,它将为您列出所有不同的内容.

which will list for you everything that is different by comparing only name and length of the file objects in each collection.

您可以将其传送到 Where-Object 过滤器以选择左侧不同的内容...

You can pipe that to a Where-Object filter to pick stuff that is different on the left side...

Compare-Object $Folder1 $Folder2 -Property Name, Length |Where-Object {$_.SideIndicator -eq "<="}

然后将其通过管道传输到 ForEach-Object 以复制您想要的位置:

And then pipe that to a ForEach-Object to copy where you want:

Compare-Object $Folder1 $Folder2 -Property Name, Length  | Where-Object {$_.SideIndicator -eq "<="} | ForEach-Object {
        Copy-Item "C:Folder1$($_.name)" -Destination "C:Folder3" -Force
        }

这篇关于使用 PowerShell 比较文件夹和内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆