【问题标题】:What is the meaning of Powershell's Copy-Item's -container argument?Powershell Copy-Item -container 参数的含义是什么?
【发布时间】:2010-09-12 20:19:17
【问题描述】:

我正在为 MS PowerShell 编写脚本。该脚本使用Copy-Item 命令。此命令的可选参数之一是“-container”。该参数的文档指出,指定此参数“在复制操作期间保留容器对象。”

这一切都很好,因为我将是最后一个在复制操作期间想要未保存的容器对象的人。但说真的,这个论点有什么用呢?特别是在我将磁盘目录树从一个地方复制到另一个地方的情况下,这对Copy-Item 命令的行为有什么影响?

【问题讨论】:

    标签: powershell copy-item


    【解决方案1】:

    文档所讨论的容器是文件夹结构。如果您正在执行递归复制并希望保留文件夹结构,则可以使用 -container 开关。 (注意:默认情况下,-container 开关设置为 true,因此您实际上不需要指定它。如果您想关闭它,可以使用 -container: $false。)

    有一个问题...如果您列出目录并将其通过管道传送到 Copy-Item,它将不会保留文件夹结构。如果要保留文件夹结构,则必须指定 -path 属性和 -recurse 开关。

    【讨论】:

      【解决方案2】:

      我也发现文档帮助不大。我做了一些测试,看看在复制文件和文件夹时-Container 参数如何与-Recurse 一起工作。

      注意-Container 表示-Container: $true

      这是我用于示例的文件结构:

      #    X:.
      #    ├───destination
      #    └───source
      #        │   source.1.txt
      #        │   source.2.txt
      #        │
      #        └───source.1
      #                source.1.1.txt
      
      • 对于所有示例,当前位置 (pwd) 为 X:\
      • 我使用的是 PowerShell 4.0。

      1) 仅复制源文件夹(空文件夹):

      Copy-Item -Path source -Destination .\destination
      Copy-Item -Path source -Destination .\destination -Container
      #    X:.
      #    ├───destination
      #    │   └───source
      #    └───source (...)
      

      以下给出错误:

      Copy-Item -Path source -Destination .\destination -Container: $false
      # Exception: Container cannot be copied to another container. 
      #            The -Recurse or -Container parameter is not specified.     
      

      2) 用文件复制整个文件夹结构:

      Copy-Item -Path source -Destination .\destination -Recurse
      Copy-Item -Path source -Destination .\destination -Recurse -Container
      #    X:.
      #    ├───destination
      #    │   └───source
      #    │       │   source.1.txt
      #    │       │   source.2.txt
      #    │       │
      #    │       └───source.1
      #    │               source.1.1.txt
      #    └───source (...)    
      

      3) 将所有后代(文件和文件夹)复制到一个文件夹中:

      Copy-Item -Path source -Destination .\destination -Recurse -Container: $false
      #    X:.
      #    ├───destination
      #    │   │   source.1.1.txt
      #    │   │   source.1.txt
      #    │   │   source.2.txt
      #    │   │
      #    │   └───source.1
      #    └───source (...)
      

      【讨论】:

      • 这个答案值得更多投票。它没有留下任何想象。 +1
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-10-14
      • 1970-01-01
      • 2012-12-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多