Powershell 文件比较 [英] Powershell File Compare
问题描述
我正在使用 PowerShell 脚本在某些服务器上移动某些文件.我想测试我要移动的文件是否已存在于目标中.不只是同名的文件.
I am using a PowerShell script to move some files around on some servers. I want to test if a file I am going to move already exists in the destination. Not just a file with the same name.
我以为
比较对象 $File1 $File2
应该这样做,但无论文件是什么,它总是返回它们是相同的例如.
Compare-Object $File1 $File2
Should do it but no matter what the files are it always returns that they are the same
eg.
InputObject SideIndicator
----------- -------------
D:\1.gif =>
D:\1.wma <=
是否有其他方法可以测试两个文件是否相同?
Is there some other way to test if two files are identical?
推荐答案
我想这取决于你对相同"的定义
I guess it's going to depend on your definition of "The same"
Compare-Object (ls Source\Test.*) (ls Dest\Test.*) -Property Name, Length, LastWriteTime
这将按名称、长度和修改日期比较实际的 FILE 对象.添加 -IncludeEqual 将导致同时显示两个地方相同的内容.
That will compare the actual FILE objects by name, length, and modified date. Adding -IncludeEqual will result in also showing ones that are the same in both places.
如果您只想从源"中复制与目标"中不同的文件,请执行以下操作:
If you want to only copy files from "Source" which aren't the same in the "Destination" just do this:
Compare-Object (ls $Source) (ls $Destination) -Property Name, Length, LastWriteTime -passthru |
Where { $_.PSParentPath -eq (gi $Source).PSPath } |
Copy-Item $Destination
不要开始编写获取内容的脚本(如其他人所建议的)来进行文件比较——您会将所有内容加载到内存中...
DO NOT start writing scripts that get-content (as suggested by others) to do a file comparison -- you'd be loading everything into memory...
请考虑使用 robocopy(即使它的命令行语法已经过时).=Þ
DO consider using robocopy (even though it's command-line syntax is dated). =Þ
这篇关于Powershell 文件比较的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!