重命名文件(如果已存在) [英] Copy files renaming if already exists PowerShell
本文介绍了重命名文件(如果已存在)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
此脚本可在复制文件时重命名文件(如果它们是重复的).我需要先重命名当前的目标文件,然后按原样复制源文件.有什么想法吗?
This script works to rename files while copying them if they are duplicates. I need to rename the current destination file first then copy the source file as is. Any ideas?
function Copy-FilesWithVersioning{
Param(
[string]$source,
[string]$destination
)
Get-ChildItem -Path $source -File
ForEach-Object {
$destinationFile = Join-Path $destination $file.Name
if ($f = Get-Item $destinationFile -EA 0) {
# loop for number goes here
$i = 1
$newname = $f.Name -replace $f.BaseName, "$($f.BaseName)_$I")
Rename-Item $destinationFile $newName
}
Copy-Item $_ $destination
}
}
Copy-FilesWithVersioning c:\scripts\Source c:\scripts\DestinationA
错误:
At line:10 char:53
+ if($f = Get-Item $destinationFile -EA 0){
+ ~
Missing closing '}' in statement block or type definition.
At line:8 char:23
+ ForEach-Object{
+ ~
Missing closing '}' in statement block or type definition.
At line:2 char:34
+ function Copy-FilesWithVersioning{
+ ~
Missing closing '}' in statement block or type definition.
At line:13 char:77
+ ... $newname = $f.Name -replace $f.BaseName, "$($f.BaseName)_$I")
+ ~
Unexpected token ')' in expression or statement.
At line:15 char:13
+ }
+ ~
Unexpected token '}' in expression or statement.
At line:17 char:9
+ }
+ ~
Unexpected token '}' in expression or statement.
At line:18 char:1
+ }
+ ~
Unexpected token '}' in expression or statement.
+ CategoryInfo : ParserError: (:) [], ParentContainsErrorRecordException
+ FullyQualifiedErrorId : MissingEndCurlyBrace
推荐答案
从此链接尝试代码: https://www.pdq.com/blog/copy-individual-files-and-rename-duplicates/:
$SourceFile = "C:\Temp\File.txt"
$DestinationFile = "C:\Temp\NonexistentDirectory\File.txt"
If (Test-Path $DestinationFile) {
$i = 0
While (Test-Path $DestinationFile) {
$i += 1
$DestinationFile = "C:\Temp\NonexistentDirectory\File$i.txt"
}
} Else {
New-Item -ItemType File -Path $DestinationFile -Force
}
Copy-Item -Path $SourceFile -Destination $DestinationFile -Force
这篇关于重命名文件(如果已存在)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文