如果源上没有文件,则比较对象删除文件

时间:2016-12-16 03:51:45

标签: powershell

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

例如说我有文件夹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
        }
    }

是否有额外的Where-Object {$ file1<> $ file2}或类似的东西。?

干杯。

4 个答案:

答案 0 :(得分: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属性而不是日期/时间。

执行此操作后,您需要更改部分脚本才能继续工作。

答案 1 :(得分: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
}

希望它好起来!

答案 2 :(得分:0)

如果我没有弄错,问题是您的代码正在删除与源相比具有不同时间戳的文件:  你有没有尝试过-ExcludeProperty?

data_json = [{"id": 12, "field_to_be_removed": {"set": null}}]

req = urllib2.Request(url="http://stg.solr.freshersworld.com/solr/collection1/update/json'",data=data_json)
req.add_header('Content-type', 'application/json')
f = urllib2.urlopen(req)

答案 3 :(得分:0)

尝试类似这样的事情

PowerShell V5中的

 $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

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