Допустим, я хочу скопировать файл test.txt в другую папку, но я хочу, чтобы он создал копию, а не просто удалил файл.
Я знаю, что Copy-Item перезаписывает файлв папке назначения, но я не хочу, чтобы это делалось.
Copy-Item
Это также должна быть функция
Даже если я не самый элегантный способ, вы можете попробовать что-то вроде этого
$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 } }
for-loop
$MAX_TRIES
regEx
test(1).txt
test(2).txt
if
elseif
$safename
else
Я думаю, что это поможет вам:
$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