如何使用powershell创建副本而不覆盖原始文件
假设我想把test.txt文件复制到另一个文件夹,但我想让它创建一个副本,而不仅仅是删除文件 我知道如何使用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
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