【问题标题】:Compare-Object Delete File if file does not exist on source如果源上不存在文件,则比较对象删除文件
【发布时间】:2016-12-16 03:51:45
【问题描述】:

我有这个 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
        }
    }

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

【问题讨论】:

    标签: powershell


    【解决方案1】:

    我不确定您是如何获得$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 属性,而不是日期/时间。

    您需要在执行此操作后更改一些脚本才能使其仍然有效。

    【讨论】:

    • 是的,这是我正在使用的代码 $source = Get-ChildItem $pathofSourceFiles -Recurse |排除目录 $excludedDirectories $destination = Get-ChildItem $pathofDestination -Recurse | Exclude-Directories $excludedDirectoriessing 获取信息:
    • 但是就像我之前提到的,这段代码适用于具有相同名称但日期/时间不同的文件,但当文件夹时则不然......
    【解决方案2】:

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

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

    【讨论】:

    • Compare-Object -Property 上的信息是根据 MSDN 指定要比较的引用和差异对象的属性数组。如果我唯一的 -Property 是 Name 为什么它会关心日期/时间。就像我之前说的,它对文件非常有效,但是如果 2 个文件夹的日期不同但名称相同,它就会有所不同
    【解决方案3】:

    以下脚本可以满足您的目的

    $Item1=Get-ChildItem 'SourcePath'
    $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
    }
    

    【讨论】:

    • 谢谢,我想这基本上就是我刚刚重构的内容。
    • 上面的代码完成了你所要求的工作
    【解决方案4】:

    试试这样的

    在 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 选项。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-04-16
      • 1970-01-01
      • 1970-01-01
      • 2016-03-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-07-22
      相关资源
      最近更新 更多