在复制之前,PowerShell复制项会检查目标文件名是否相同

时间:2019-01-17 05:03:33

标签: powershell

我有一个脚本

  1. 排序文件和文件夹。
  2. 在检查可用空间的同时将递归排序的文件有选择地复制到多个位置。
  3. 重命名某些复制文件的扩展名。

脚本运行平稳。但是,如果我运行脚本两次,由于某些扩展名已重命名,“复制”部分将复制重复文件。 (问题仅适用于重命名的扩展名)

我想不出一种更好的方法,那就是在递归和提取基本名称并对照目标中的现有文件进行检查时获取每个文件。但是有数千个文件要处理。因此效率不高。

目录结构:

  • 主要
  • SUB1
    • date1
    • date2
    • date3
      • folder1
      • folder2
      • folder3
      • 文件夹4
        • file_1.extension
        • file_2.extension
        • file_3.extension
  • SUB2

    • date1
    • date2
    • date3
      • category_1
      • category_2
      • category_3
        • sub_cat_1
        • sub_cat_2
        • sub_cat_3
          • file_1.new_extension
          • file_2.new_extension
          • file_3.new_extension
  • 每个月的每个日期下都有每个文件和文件夹。

  • 我将文件从SUB1复制到SUB2

这是我的复制功能之一

$threshold = 100    
function Copy-1 {

$rmainingSpace = Get-FreeSpace

if($rmainingSpace -gt $threshold)
        {
           $Source = "source\path"

                Copy-Item ($Source) -Destination "destination\path" -Filter "*.extension" -recurse -Verbose 

                Copy-Item ($Source) -Destination "some\other\destination\path" -Filter "*.another_extension" -recurse -Verbose 

            $rmainingSpace = Get-FreeSpace

        }
        else
        {
            Pause($rmainingSpace)
            Copy-1
        }
}
  • 暂停功能暂停脚本,直到按Enter。这样,如果磁盘空间用完了,我可以清除空间并继续执行脚本的其余部分。
  • 几乎没有其他类似于此功能的复制功能。我使用多种复制功能,根据需要将文件放到不同的位置复制到不同的位置。

非常感谢任何人都可以提供帮助。 谢谢。

1 个答案:

答案 0 :(得分:0)

正如Kory Gill的注释一样,我也看不到为什么要更改文件扩展名。 我的想法是,如果目标文件应该已经存在,则在文件的基本名称上添加一个序号。
实际上,如果您手动尝试复制/粘贴已经存在的文件,Windows也会建议在文件中添加序列号。

为此,此功能可能很有用:

function Copy-Unique {
    # Copies files to a destination. If a file with the same name already exists in the destination,
    # the function will create a unique filename by appending '(x)' after the name, but before the extension. 
    # The 'x' is a numeric sequence value.
    [CmdletBinding()]
    Param(
        [Parameter(Mandatory = $true, ValueFromPipeline = $true, Position = 0)]
        [Alias("Path")]
        [ValidateScript({Test-Path -Path $_ -PathType Container})]
        [string]$SourceFolder,

        [Parameter(Mandatory = $true, Position = 1)]
        [string]$DestinationFolder,

        [Parameter(Mandatory = $false, Position = 2)]
        [string]$Filter = '*',

        [switch]$Recurse
    )

    # create the destination path if it does not exist
    if (!(Test-Path -Path $DestinationFolder -PathType Container)) {
        Write-Verbose "Creating folder '$DestinationFolder'"
        New-Item -Path $DestinationFolder -ItemType 'Directory' -Force | Out-Null
    }
    # get a list of file FullNames in this source folder
    $sourceFiles = @(Get-ChildItem -Path $SourceFolder -Filter $Filter -File | Select-Object -ExpandProperty FullName)
    foreach ($file in $sourceFiles) {
        # split each filename into a basename and an extension variable
        $baseName  = [System.IO.Path]::GetFileNameWithoutExtension($file)
        $extension = [System.IO.Path]::GetExtension($file)    # this includes the dot

        # get an array of all filenames (names only) of the files with a similar name already present in the destination folder
        $allFiles = @(Get-ChildItem $DestinationFolder -File -Filter "$baseName*$extension" | Select-Object -ExpandProperty Name)
        # for PowerShell version < 3.0 use this
        # $allFiles = @(Get-ChildItem $DestinationFolder -Filter "$baseName*$extension" | Where-Object { !($_.PSIsContainer) } | Select-Object -ExpandProperty Name)

        # construct the new filename
        $newName = $baseName + $extension
        $count = 1
        while ($allFiles -contains $newName) {
            $newName = "{0}({1}){2}" -f $baseName, $count, $extension
            $count++
        }
        # use Join-Path to create a FullName for the file
        $newFile = Join-Path -Path $DestinationFolder -ChildPath $newName
        Write-Verbose "Copying '$file' as '$newFile'"

        Copy-Item -Path $file -Destination $newFile -Force
    }
    if ($Recurse) {
        # loop though each subfolder and call this function again
        Get-ChildItem -Path $SourceFolder -Directory | Select-Object -ExpandProperty Name | ForEach-Object {
            $newSource = (Join-Path -Path $SourceFolder -ChildPath $_)
            $newDestination = (Join-Path -Path $DestinationFolder -ChildPath $_)
            Copy-Unique -SourceFolder $newSource -DestinationFolder $newDestination -Filter $Filter -Recurse
        }
    }
}

我还建议您对Copy-1函数进行一些更改,以使用上述Copy-Unique函数:

function Copy-1 {
    [CmdletBinding()]
    Param(
        [Parameter(Mandatory = $true, Position = 0)]
        [Alias("Path")]
        [ValidateScript({Test-Path -Path $_ -PathType Container})]
        [string]$Source,

        [Parameter(Mandatory = $true, Position = 1)]
        [string]$Destination,

        [Parameter(Mandatory = $true, Position = 2)]
        [int]$Threshold,

        [string]$Filter = '*'
    )

    # you are not showing this function, so I have to assume it does what it needs to do
    $remainingSpace = Get-FreeSpace

    if($remainingSpace -gt $Threshold) {
        Copy-Unique -SourceFolder $Source -DestinationFolder $Destination -Filter $Filter -Recurse -Verbose
    }
    else {
        $answer = Read-Host -Prompt "Remaining space is now $remainingSpace. Press 'Q' to quit."
        if ($answer -ne 'Q') {
            # you have cleared space, and want to redo the copy action
            Copy-1 -Source $Source -Destination $Destination -Filter $Filter
        }
    }
}

然后像这样使用它:

Copy-1 -Source 'source\path' -Destination 'destination\path' -Threshold 100 -Filter '*.extension'
Copy-1 -Source 'source\path' -Destination 'some\other\destination\path' -Threshold 100 -Filter '*.another_extension'


注意

当然,使用相同的参数重复运行此操作,最终会得到很多副本,因为该功能不会比较文件是否相等。如果要进行真正的文件夹同步,建议您使用专用的软件或使用RoboCopy。 使用RoboCopy进行目录同步的示例几乎可以在互联网上的任何地方找到,例如here

相关问题