Powershell 5 将项目目录复制到目录错误

Powershell 5 Copy-Item Directory to Directory Error

我是 Powershell 的新手,正在根据 this documentation 测试 Copy-Item 的功能。我正在尝试将子文件夹中的文件和文件夹复制到它的包含文件夹中,但它不起作用。我需要使用什么命令?

这是我的示例文件结构

C:\
    Example
    |
    |__Top
        |
        |__Middle
            |
            |__Bottom

我尝试使用

将所有文件和子文件夹从Middle复制到Top
Copy-Item "C:\Example\Top\Middle" -Destination "C:\Example\Top" -Recurse

但收到此错误

Copy-Item : An item with the specified name C:\Example\Top\Middle already exists.
At line:1 char:1
+ Copy-Item "C:\Example\Top\Middle" -Destination "C:\Example\Top" -Recu ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : ResourceExists: (C:\Example\Top\Middle:String) 
[Copy-Item], IO
   Exception
    + FullyQualifiedErrorId : 
DirectoryExist,Microsoft.PowerShell.Commands.CopyItemCommand

Copy-Item : Cannot overwrite the item C:\Example\Top\Middle\InTheMiddle.txt 
with itself.
At line:1 char:1
+ Copy-Item "C:\Example\Top\Middle" -Destination "C:\Example\Top" -Recu ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : WriteError: 
(C:\Example\Top\Middle\InTheMiddle.txt:String) [Co
   py-Item], IOException
    + FullyQualifiedErrorId : 
CopyError,Microsoft.PowerShell.Commands.CopyItemCommand

Copy-Item : An item with the specified name C:\Example\Top\Middle\Bottom already         
exists.
At line:1 char:1
+ Copy-Item "C:\Example\Top\Middle" -Destination "C:\Example\Top" -Recu ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : ResourceExists: 
(C:\Example\Top\Middle\Bottom:String) [Copy-It
   em], IOException
    + FullyQualifiedErrorId : 
DirectoryExist,Microsoft.PowerShell.Commands.CopyItemCommand

Copy-Item : Cannot overwrite the item 
C:\Example\Top\Middle\Bottom\InTheBottom.txt with
itself.
At line:1 char:1
+ Copy-Item "C:\Example\Top\Middle" -Destination "C:\Example\Top" -Recu ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : WriteError: 
(C:\Example\Top\...InTheBottom.txt:String) [Copy-I
   tem], IOException
    + FullyQualifiedErrorId : 
CopyError,Microsoft.PowerShell.Commands.CopyItemCommand

Powershell 版本 5.1.17134.112 运行 作为管理员

我相信这将作为最简单的示例完成您正在寻找的内容。它需要根据您的情况进行调整。

-需要施加强制才能覆盖。

$source = "C:\Example\Top\Middle\*"

$destination = "C:\Example\Top\"

Copy-Item -Path $source -Destination $destination -Include *.*

您正在尝试将子文件夹复制到其父文件夹。要复制 "Middle" 文件夹的内容,您需要使用此命令:

Copy-Item "C:\Example\Top\Middle\*" -Destination "C:\Example\Top" -Recurse