如何使用powershell创建副本而不覆盖原始文件

如何使用powershell创建副本而不覆盖原始文件,powershell,Powershell,假设我想把test.txt文件复制到另一个文件夹,但我想让它创建一个副本,而不仅仅是删除文件 我知道Copy Item会覆盖目标文件夹中的文件,但我不希望它这样做 它还必须是一个函数我认为这将帮助您: $destinationFolder = 'PATH OF THE DESTINATION FOLDER' $sourceFile = 'FULL PATH AND FILENAME OF THE SOURCE FILE' # split the filename into a b

假设我想把test.txt文件复制到另一个文件夹,但我想让它创建一个副本,而不仅仅是删除文件

我知道
Copy Item
会覆盖目标文件夹中的文件,但我不希望它这样做


它还必须是一个函数

我认为这将帮助您:

$destinationFolder = 'PATH OF THE DESTINATION FOLDER'
$sourceFile        = 'FULL PATH AND FILENAME OF THE SOURCE FILE'

# split the filename into a basename and an extension variable
$baseName  = [System.IO.Path]::GetFileNameWithoutExtension($sourceFile)
$extension = [System.IO.Path]::GetExtension($sourceFile)
# you could also do it like this:
#   $fileInfo = Get-Item -Path $sourceFile
#   $baseName = $fileInfo.BaseName
#   $extension = $fileInfo.Extension

# get an array of all filenames (name 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)

# construct the new filename
$newName = $baseName + $extension
$count = 1
while ($allFiles -contains $newName) {
    # add a sequence number in brackets to the end of the basename until it is unique in the destination folder
    $newName = "{0}({1}){2}" -f $baseName, $count++, $extension
}

# construct the new full path and filename for the destination of your Copy-Item command
$targetFile = Join-Path -Path $destinationFolder -ChildPath $newName

Copy-Item -Path $sourceFile -Destination $targetFile

即使我不是最优雅的方式,你也可以尝试这样的方式

$src = "$PSScriptRoot"
$file = "test.txt"
$dest = "$PSScriptRoot\dest"
$MAX_TRIES = 5
$copied = $false

for ($i = 1; $i -le $MAX_TRIES; $i++) {
    if (!$copied) {
        $safename = $file -replace "`.txt", "($i).txt"
        if (!(Test-Path "$dest\$file")) {
            Copy-Item "$src\$file" "$dest\$file"
            $copied = $true
        } elseif (!(Test-Path "$dest\$safename")) {
            Copy-Item "$src\$file" "$dest\$safename"
            $copied = $true
        } else {
            Write-Host "Found existing file -> checking for $safename"
        }
    } else {
        break
    }
}
  • 循环的
    将尝试安全地复制文件最多5次(由
    $MAX\u trys
    确定)
    • 如果5次还不够,什么也不会发生
  • regEx
    将创建
    test(1.txt
    test(2.txt
    。。。检查要复制的“安全”文件名
  • if
    -语句将检查是否可以复制原始文件
  • elseif
    -语句将尝试使用上面创建的
    $safename
  • else
    -语句只是打印了一个关于发生了什么的“提示”

指定一个不同的文件名。是否有办法使我的文件名相同,但后面加上和数字,如(1)?或将文件放在不同的文件夹中。我遇到的问题是,我必须从一个文件夹复制到另一个文件夹,在这种情况下,更改文件夹不是一个选项。文件可能重复。