2016-12-16 62 views
-1

我有这个PowerShell代码比较2个目录,并删除文件,如果文件不再存在于源目录中。比较对象删除文件,如果源文件不存在

例如说我有文件夹1个&文件夹2.我想比较文件夹1文件夹2,如果一个文件不存在了的文件夹1它将从文件夹2.

这个代码删除工作好,但我有一个问题,它也在日期/时间挑选文件的差异。我只希望它拿起区别,如果文件没有在文件夹1.

Compare-Object $source $destination -Property Name -PassThru | Where-Object {$_.SideIndicator -eq "=>"} | % { 
     if(-not $_.FullName.PSIsContainer) { 
      UPDATE-LOG "File: $($_.FullName) has been removed from source" 
      Remove-Item -Path $_.FullName -Force -ErrorAction SilentlyContinue 
     } 
    } 

存在了有一个额外的位置对象{$文件1 <> $文件2}或类似的东西?

干杯。

回答

0

我不知道你是如何获取信息$source$destination我假设你正在使用Get-ChildItem

我会做什么,以消除日期的问题/时间将无法捕捉到它在这些变量。例如:

$source = Get-ChildItem C:\temp\Folder1 -Recurse | select -ExpandProperty FullName 
$destination = Get-ChildItem C:\temp\Folder2 -Recurse | select -ExpandProperty FullName 

通过这样做,你只能得到FullName物业这是一个子项不日期/时间每个对象。

这样做后,您需要更改一些脚本才能继续工作。

+0

是这是我正在使用的代码 $ source = Get-ChildItem $ pathofSourceFiles -Recurse |排除目录$ excludedDirectories $ destination = Get-ChildItem $ pathofDestination -Recurse |排除目录$ excludedDirectoriessing获取信息: –

+0

但就像我之前提到的,此代码工作正常的文件具有相同的名称,但日期/时间是不同的,但并非如此当一个文件夹.. –

0

下面的脚本可以服务器的目的

$Item1=Get-ChildItem 'SourecPath' 
$Item2=Get-ChildItem 'DestinationPath' 

$DifferenceItem=Compare-Object $Item1 $Item2 

$ItemToBeDeleted=$DifferenceItem | where {$_.SideIndicator -eq "=>" } 



foreach ($item in $ItemToBeDeleted) 
{ 
    $FullPath=$item.InputObject.FullName 

    Remove-Item $FullPath -Force 
} 

希望它能帮助!

+0

谢谢,我认为这是基本上我所得到的只是反映了一点。 –

+0

上述代码完成了您所要求的工作 – Venkatakrishnan

0

如果我没有得到它的错误,问题是你的代码是删除文件与源相比有不同的时间戳: 您是否尝试过-ExcludeProperty?在PowerShell中V5

$source = Get-ChildItem "E:\New folder" -Recurse | select -ExcludeProperty Date 
+0

Compare-Object -Property上的信息是根据MSDN 指定要比较的参考和差异对象的属性数组。 如果我唯一的 - 属性是名称它为什么关心日期/时间。像我之前说过的,它对于文件来说工作得很好,但是如果2个文件夹有不同的日期,但是名称相同,它会带来不同 –

0

尝试这样的事情

$yourdir1="c:\temp" 
$yourdir2="c:\temp2" 

$filesnamedir1=(gci $yourdir1 -file).Name 
gci $yourdir2 -file | where Name -notin $filesnamedir1| remove-item 
旧的PowerShell

$yourdir1="c:\temp" 
$yourdir2="c:\temp2" 

$filesnamedir1=(gci $yourdir1 | where {$_.psiscontainer -eq $false}).Name 
gci $yourdir2 | where {$_.psiscontainer -eq $false -and $_.Name -notin $filesnamedir1} | remove-item 

如果你想比较多个目录文件,在每添加-recurse选项

gci命令

相关问题