复制文件重命名(如果已存在 PowerShell)



此脚本用于重命名文件,同时复制文件(如果它们是重复的(。 我需要先重命名当前目标文件,然后按原样复制源文件。 有什么想法吗?

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:scriptsSource c:scriptsDestinationA

错误:

行:10 字符:53 + if($f = 获取项 $destinationFile -EA 0({ +                                                     ~ 语句块或类型定义中缺少结束"}"。 行:8 字符:23 + forEach-Object{ +                       ~ 语句块或类型定义中缺少结束"}"。 行:2 字符:34 + 函数 Copy-FilesWithVersioning{ +                                  ~ 语句块或类型定义中缺少结束"}"。 行:13 字符:77 + ... $newname = $f.Name -替换 $f.BaseName, "$($f.BaseName(_$I"( +                                                                         ~ 表达式或语句中出现意外的标记"("。 行:15 字符:13 +             } +             ~ 表达式或语句中出现意外的标记"}"。 行:17 字符:9 +         } +         ~ 表达式或语句中出现意外的标记"}"。 行:18 字符:1 + } + ~ 表达式或语句中出现意外的标记"}"。 + 类别信息:解析器错误:(:) [],父包含错误记录异常 + 完全限定错误 ID:缺少端花括号

您看到的错误是由此行中的虚假右括号引起的:

$newname = $f.Name -replace $f.BaseName, "$($f.BaseName)_$I")

从行尾删除括号,这些错误将消失。

但是,您的代码中还有其他几个错误,因此即使修复了错误,代码仍然无法正常工作。

  • 您在Get-ChildItemForEach-Object之间缺少管道。将一个 cmdlet 的输出传递给另一个 cmdlet 是必需的。

    Get-ChildItem -Path $source -File |
    ForEach-Object {
    ...
    }
    
  • 变量$file未定义。在 PowerShell 管道中,你想要使用"当前对象"变量 ($_(。更改此行

    $destinationFile = Join-Path $destination $file.Name
    

    $destinationFile = Join-Path $destination $_.Name
    
  • 声明中的$_

    Copy-Item $_ $destination
    

    仅扩展为文件的名称,而不是完整路径。将其更改为

    Copy-Item $_.FullName $destination
    

    更好的是,将Copy-Item语句移到ForEach-Object之后,这样就不需要首先显式指定源(cmdlet 从管道读取输入(:

    Get-ChildItem ... | ForEach-Object {
    ...
    $_   # need this line to pass the current object back into the pipeline
    } | Copy-Item -Destination $destination
    

    请注意,您必须将当前对象输出回管道,并将目标指定为命名参数 (-Destination $destination(,后者才能正常工作。

  • 检查目标文件夹中是否存在文件有点尴尬。请改用Test-Path。您可以从当前对象构造新文件名。

    if (Test-Path -LiteralPath $destinationFile) {
    $i = 1
    Rename-Item $destinationFile ($_.BaseName + "_$i" + $_.Extension)
    }
    

从以下链接尝试代码: https://www.pdq.com/blog/copy-individual-files-and-rename-duplicates/:

$SourceFile = "C:TempFile.txt"
$DestinationFile = "C:TempNonexistentDirectoryFile.txt"
If (Test-Path $DestinationFile) {
$i = 0
While (Test-Path $DestinationFile) {
$i += 1
$DestinationFile = "C:TempNonexistentDirectoryFile$i.txt"
}
} Else {
New-Item -ItemType File -Path $DestinationFile -Force
}
Copy-Item -Path $SourceFile -Destination $DestinationFile -Force 

最新更新