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

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

问题描述

PowerShell noob这里。



我有两个不同的xml文件夹。一个文件夹(folder2)包含已更新的和新的xml文件相比,其他(folder1)。我需要知道folder2中的哪些文件是新的/更新与folder1相比,并将其复制到第三个文件夹(folder3)。

解决方案

确定,我不打算为你编写整个代码



首先,有两种方法来进行内容比较。 lazy /大多正确的方式,它是比较文件的长度;并且准确但更多涉及的方式,这是比较每个文件的内容的散列。



为了简单起见,让我们做简单的方法和比较文件大小。 / p>

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

  $ Folder1 = Get-childitemC:\Folder1
$ Folder2 = Get-childitemC:\Folder2

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



比较对象$ Folder1 $ Folder2 -Property名称,长度





您可以将其转换为 Where-Object

code>过滤器选择左侧不同的东西...



比较对象$ Folder1 $ Folder2 -Property名称,Length | Where-Object {$ _。SideIndicator -eq< =}



然后管道到 ForEach-Object 复制所需位置:

 比较对象$ Folder1 $ Folder2  - 属性名称,Length | Where-Object {$ _。SideIndicator -eq< =} | ForEach-Object {
Copy-ItemC:\Folder1\ $($ _。name)-DestinationC:\Folder3-Force
}


PowerShell noob here.

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"

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.

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 "<="}

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天全站免登陆