【问题标题】:Merge two directories keeping any files with same name合并两个目录,保留任何同名文件
【发布时间】:2016-12-08 17:40:15
【问题描述】:

我正在寻找一些帮助来创建一个 PowerShell 脚本以将一个目录合并或复制到另一个目录,其中目标目录具有与源同名的文件。

我需要保留两者,如果脚本在目标中有一个重名的文件,则脚本可以在源文件中附加一个数字。

Here 是一个处理一个文件的示例脚本,但我需要设置一个目录并让它在整个目录上递归释放。

$SourceFile = "C:\Temp\File.txt"
$DestinationFile = "C:\Temp\NonexistentDirectory\File.txt"

if ((Test-Path $DestinationFile) -eq $false) {
    New-Item -ItemType File -Path $DestinationFile -Force
}

Copy-Item -Path $SourceFile -Destination $DestinationFile

【问题讨论】:

  • 通过要处理的数据示例和预期结果向我们展示您目前拥有的数据。顺便说一句 - cmd.exe - .com 文件已被禁用很长时间。
  • 我将问题更改为使用 powershell,谢谢,到目前为止我没有任何代码,但我确实有一些示例。如果可以发布其他作品,我会发布它
  • 有子文件夹吗?他们也要搬家吗?如果一个文件已经有一个附加的数字,增加这个数字或添加另一个词缀怎么办?如果词缀用下划线分隔或括在括号中 (1) 我不会复制而是移动/重命名文件。

标签: powershell


【解决方案1】:

试试这个

$SourceDir = "C:\Temp"
$DestinationDir = "C:\Temp2\NonexistentDirectory"

#create dir if not exists (dont remove if exist)
New-Item -ItemType Directory -Path $DestinationDir -Force

#get list files destination dir 
$DestinationFiles=gci $DestinationDir -File

#loop on file source and create newname for copy while name exist already
gci $SourceDir -File | %{

$counter=0
$name=$_.Name
while ($name -in $DestinationFiles.Name)
{
  $counter++;
  $name="{0}_{1:d6}{2}" -f  $_.BaseName, $counter, $_.Extension

}


Copy-Item -Path $_.FullName -Destination "$DestinationDir\$name" 

}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-13
    • 2021-09-26
    • 2019-06-28
    • 2021-06-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多