代码之家  ›  专栏  ›  技术社区  ›  garfbradaz Vivek

PowerShell复制到-如果目标目录存在,则复制到现有目录

  •  1
  • garfbradaz Vivek  · 技术社区  · 7 年前

    对,我有一个简单的 Copy-Item 用于将文件从一个目标文件夹复制到另一个目标文件夹的脚本。

    释放程序PS1

    [CmdletBinding()]
    param(
        [Parameter(Mandatory=$true)]
        [string]$source, 
        [Parameter(Mandatory=$true)]
        [string]$destination
    ) 
    Process {
        Copy-Item -Path $source -Destination $destination -Recurse -Force
    

    我在跑步 releasecode.ps1 使用以下命令行:

    .\releasecode.ps1-源“c:\test\from”-目标“c:\test\to”

    这个 from 文件夹具有以下结构:

    .
    ├── from
    ├── stain.txt
    ├── test1.txt
    ├── folder
    |   ├── test2.bmp
    

    这正确地复制到 第一副本 ):

    .
    ├── to
    ├── stain.txt
    ├── test1.txt
    ├── folder
    |   ├── test2.bmpthe 
    

    如果之后我直接重新运行它, 文件夹创建为“to”中的目录,而不是覆盖现有结构:

    .
    ├── to
    ├── stain.txt
    ├── test1.txt
    ├── folder
    |   ├── test2.bmp
    ├── from
    |   ├── stain.txt
    |   ├── test1.txt
    |   └── folder
    |       ├── test2.bmp
    

    如何覆盖现有的 to 目录结构(如果文件和文件夹当前存在)。

    更多信息

    • 在Windows设备上运行

    • $PSVersionTable 以下内容:

    enter image description here

    1 回复  |  直到 7 年前
        1
  •  1
  •   Ansgar Wiechers    7 年前

    你遇到了一个 Copy-Item 找到与复制源目录相关的。

    如果目标存在并且是文件夹,则Cmdlet将复制源 目的地。

    Copy-Item C:\src\a C:\dst\b -Recurse
    
    C:\                 C:\
    ├─dst               ├─dst
    | └─b               | └─b
    └─src               |   └─a
      └─a           ⇒   |     ├─bar.txt
        ├─bar.txt       |     └─baz.txt
        └─baz.txt       └─src
                          └─a
                            ├─bar.txt
                            └─baz.txt
    

    如果目标不存在,则Cmdlet将复制源 作为 目的地。

    Copy-Item C:\src\a C:\dst\b -Recurse
    
    C:\                 C:\
    ├─dst               ├─dst
    └─src               | └─b
      └─a               |   ├─bar.txt
        ├─bar.txt   ⇒   |   └─baz.txt
        └─baz.txt       └─src
                          └─a
                            ├─bar.txt
                            └─baz.txt
    

    在PowerShell中处理此问题的惯用方法是确保首先存在目标文件夹, 然后 抄袭 内容 源文件夹的:

    if (-not (Test-Path $destination)) {
        New-Item -Type Directory -Path $destination | Out-Null
    }
    Copy-Item -Path $source\* -Destination $destination -Recurse -Force
    

    或者您可以使用 robocopy ,没有此问题:

    robocopy C:\src\a C:\dst\b /s
    
    推荐文章