如何使用Powershell复制目录,并覆盖目录的内容?


9

我有一个目录Source,其中包含一些文件,我想将其复制到文件夹Destination中。目标可能存在,并且可能已经有文件。与Source中相同名称的所有文件都应被覆盖。

如果我在Powershell中运行此命令:

Copy-Item Source Destination -Force -Recurse
Copy-Item Source Destination -Force -Recurse
Copy-Item Source Destination -Force -Recurse

然后第一行创建文件夹.\Destination并将其复制.\Source到其中,这是我下一次要重复的内容。但是,第二行.\Source改为复制到新.\Destination文件夹中(正在创建.\Destination\Source),然后第三行.\Destination\Source再次覆盖。

如何使它始终像第一种情况一样工作?也就是说,覆盖.\Destination而不是复制到其中?


你能澄清一下吗?您要将“源”的内容复制到“目标”中吗?而不是将文件夹“源”复制到“目的地”?
BroScience

对,那是正确的。“目的地”文件夹可能不存在,因此如果不退出,则希望创建该文件夹。
道格拉斯

可能值得考虑使用robocopy作为替代方法。如果需要,您仍然可以从powershell调用它。它可以if exists轻松解决该问题,也不需要您强制递归删除目的地,这有其自身的危险。
杰里米

与SO密切相关的问题:stackoverflow.com/q/47964451/45375
mklement0

Answers:


7

所以问题是

cp -r -fo foo bar

仅在bar不存在时起作用,并且

cp -r -fo foo/* bar

仅在bar存在的情况下有效。因此,要解决此问题,您需要先确保bar存在,然后再执行任何操作

md -f bar
cp -r -fo foo/* bar

3

如果只想复制“源”文件夹的内容,请使用

copy-item .\source\* .\destination -force -recurse

1
这仅在destination已经存在的情况下有效。
Steven Penny

3

史蒂文·潘尼(Steven Penny)的答案https://superuser.com/a/742719/126444不会删除目标目录的原始内容,而只是将其追加到目标目录中。我需要用源内容完全替换目标文件夹并创建2个函数:

function CopyToEmptyFolder($source, $target )
{
    DeleteIfExistsAndCreateEmptyFolder($target )
    Copy-Item $source\* $target -recurse -force
}
function DeleteIfExistsAndCreateEmptyFolder($dir )
{
    if ( Test-Path $dir ) {
    #http://stackoverflow.com/questions/7909167/how-to-quietly-remove-a-directory-with-content-in-powershell/9012108#9012108
           Get-ChildItem -Path  $dir -Force -Recurse | Remove-Item -force -recurse
           Remove-Item $dir -Force

    }
    New-Item -ItemType Directory -Force -Path $dir
}

1

假设您具有以下目录结构

    • folder_a
      • a.txt
      • b.txt
      • c.txt
    • folder_b
      • a.txt
      • b.txt

    在根文件夹中,可以通过以下命令序列获得所需的结果:

    $files = gci ./folder_b -name
    cp ./folder_a/*.txt -Exclude $files ./folder_b

仅复制c.txt

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.