比较2个文件夹并将路径保存到变量中?

时间:2013-01-08 17:37:39

标签: powershell compare get-childitem

我的任务是比较2个文件夹FolderA和FolderB,并注意A中存在但不存在于B中的任何文件。

很抱歉没有完全解释自己。如果我解释一下情况,也许会有所帮助。公司销售人员离开我们公司去竞争对手。他在他的工作笔记本电脑本地硬盘上有文件。我们正在尝试确定他的计算机上是否存在任何文件但不存在于共享网络文件夹中。

我需要生成一个列表,列出他的笔记本电脑上但不在共享网络位置上的任何文件(及其路径)。笔记本电脑本地硬盘驱动器和共享网络位置之间的文件结构是不同的。什么是最好的方法呢?

$folderAcontent = "C:\temp\test1" 
$folderBcontent = "C:\temp\test2"

$FolderAContents = Get-ChildItem $folderAcontent -Recurse | where-object {!$_.PSIsContainer}
$FolderBContents = Get-ChildItem $folderBcontent -Recurse | where-object {!$_.PSIsContainer}

$FolderList = Compare-Object -ReferenceObject ($FolderAContents ) -DifferenceObject ($FolderBContents) -Property name
$FolderList | fl * 

3 个答案:

答案 0 :(得分:5)

使用compare-Object cmdlet:

Compare-Object (gci $folderAcontent) (gci $folderBcontent)

如果要列出仅在$ folderAcontent中的文件,请使用< = SideIndicator:

选择结果
Compare-Object (gci $folderAcontent) (gci $folderBcontent) | where {$_.SideIndicator -eq "<="}

答案 1 :(得分:2)

假设两个目录中的文件名相同,您可以执行以下操作: -

$folderAcontent = "C:\temp\test1"  
$folderBcontent = "C:\temp\test2"

ForEach($File in Get-ChildItem -Recurse -LiteralPath $FolderA | where {$_.psIsContainer -eq $false} | Select-Object Name)
{
   if(!(Test-Path "$folderBcontent\$File"))
{
   write-host "Missing File: $folderBcontent\$File"
}
}

以上内容仅适用于文件夹A中的文件(不是子目录)

答案 2 :(得分:1)

尝试:

#Set locations
$laptopfolder = "c:\test1"
$serverfolder = "c:\test2"

#Get contents
$laptopcontents = Get-ChildItem $laptopfolder -Recurse | where {!$_.PSIsContainer}
$servercontents = Get-ChildItem $serverfolder -Recurse | where {!$_.PSIsContainer}

#Compare on name and length and find changed files on laptop
$diff = Compare-Object $laptopcontents $servercontents -Property name, length -PassThru | where {$_.sideindicator -eq "<="}

#Output differences
$diff | Select-Object FullName

如果在compare-object cmdlet中添加lastwritetime之后,它将比较修改日期(如果文件已更新但仍然大小相同)。请注意,它只会查找不同的日期,而不是它是更新还是更旧。 :)