【问题标题】:copy newer files without keeping folders复制较新的文件而不保留文件夹
【发布时间】:2022-11-19 10:39:30
【问题描述】:

我有一个包含许多包含文件的子文件夹的文件夹,我想将所有文件复制到根文件夹,但只有更新时才覆盖。

在 powershell 中我可以做 -

获取子项 D:\VaM\Custom\Atom\Person\Morphs\temp2\female -Recurse -file |复制项目-目的地 D:\VaM\Custom\Atom\Person\Morphs\female

但这会覆盖所有文件,如果复制的文件较新,我只想覆盖文件。

robocopy 只能覆盖较旧的,但会保留文件夹结构。

【问题讨论】:

    标签: powershell copy robocopy


    【解决方案1】:

    尝试这个

    $root = 'D:VaMCustomAtomPersonMorphs	emp2emale'
    [bool]$Delete = $false
    
    Get-ChildItem $root -Recurse -File |
        Where-Object {$_.DirectoryName -ne $root } | # Do not touch files already seated in root
        ForEach-Object {
            $rootNameBrother = Get-Item "$root$($_.Name)" -ea 0
            if($rootNameBrother -and $rootNameBrother.LastWriteTime -lt $_.LastWriteTime) {
                # RootFile with same name exists and is Older - Copy and override
                Copy-Item -Path $_.FullName -Destination $rootNameBrother.FullName -Force
            }
            elseif ($rootNameBrother -and $rootNameBrother.LastWriteTime -ge $_.LastWriteTime) { 
                # RootFile with same name exists and is Newer or same Age
                # Delete non root File if allowed
                if($Delete) { Remove-Item $_.FullName -Force }
            }
        }
    

    放...

    $Delete = $true
    

    ...如果您希望删除无法复制的非根文件,因为根目录中已经有一个具有相同名称和更大修改日期的文件。

    另外,如果你想删除所有空的子文件夹,你可以运行这个:

    $allFolders =`
    Get-ChildItem $root -Recurse -Directory | 
    ForEach-Object { 
        # Add now Depth Script Property
        $_ | Add-Member -PassThru -Force -MemberType ScriptProperty -Name Depth -Value { 
            # Get Depth of folder by looping through each letter and counting the backshlashes
            (0..($this.FullName.Length - 1) | ForEach {$this.FullName.Substring($_,1)} | Where-Object {$_ -eq ""}).Count
        }
    }
    
    # Sort all Folder by new Depth Property annd Loop throught
    $allFolders | Sort -Property Depth -Descending |
    ForEach-Object {
        # if .GetFileSystemInfos() method return null, the folder is empty
        if($_.GetFileSystemInfos().Count -eq 0) { 
            Remove-Item $_.FullName -Force # Remove Folder 
        }          
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-04-17
      • 1970-01-01
      • 2019-01-23
      • 2013-06-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-03-03
      相关资源
      最近更新 更多