在 Copy-Item cmdlet 中为详细选项定义文件夹深度

Define folder depth for the verbose option in Copy-Item cmdlet

我正在使用以下命令将目录树从一个文件夹复制到另一个文件夹。

Copy-Item $SOURCE $DEST -Filter {PSIsContainer} -Recurse -Force -Verbose

详细选项正确显示了每个被复制的文件夹。但是,我想告诉 Verbose 选项只显示复制的子文件夹的第一级。因此 subfolders/subfolders/... 等不会出现。

可以吗?

我建议使用 robocopy 而不是 copy-item。它的 /LEV:n 开关听起来正是您要找的。示例(您需要测试和调整以满足您的要求):

robocopy $source $dest /LEV:2

robocopy 有大约 7 个选项,您可以指定这些选项以从中获得一些非常有用和有趣的行为。

计算路径中反斜杠的数量,并可能仅向 select 第一级添加逻辑。也许是这样的?

$Dirs=get-childitem $Source -Recurse | ?{$_.PSIsContainer}
Foreach ($Dir in $Dirs){
    $Level=([regex]::Match($Dir.FullName,"'b")).count
    if ($Level -eq 1){Copy-Item $Dir $DEST -Force -Verbose}
    else{Copy-Item $Dir $DEST -Force}}

*根据要求进行编辑以包含循环和逻辑

您可以使用 -PassThru 选项来通过管道处理成功处理的项目,而不是使用 -Verbose 选项。在下面的示例中,我假设 $DESTexisting 目录,新复制的目录将出现在该目录中。 (您不能对不存在的对象调用 Get-Item。)

$SOURCE = Get-Item "foo"
$DEST   = Get-Item "bar"

Copy-Item $SOURCE $DEST -Filter {PSIsContainer} -Recurse -Force -PassThru | Where-Object {

  # Get the parent object.  The required member is different between
  # files and directories, which makes this a bit more complex than it
  # might have been.

  if ($_.GetType().Name -eq "DirectoryInfo") {
    $directory = $_.Parent
  } else {
    $directory = $_.Directory
  }

  # Select objects as required, in this case only allow through
  # objects where the second level parent is the pre-existing target
  # directory.

  $directory.Parent.FullName -eq $DEST.FullName
}