我使用以下命令将目录树从一个文件夹复制到另一个文件夹。
Copy-Item $SOURCE $DEST -Filter {PSIsContainer} -Recurse -Force -Verbose
详细选项正确地显示了所复制的每个文件夹。但是,我想告诉"详细"选项只显示复制的子文件夹的第一级。因此,子文件夹/子文件夹/。。。等等都不会出现。
有可能吗?
您可以使用-PassThru
选项通过管道处理成功处理的项目,而不是使用-Verbose
选项。在下面的示例中,我假设$DEST
是现有目录,新复制的目录将出现在该目录中。(不能在不存在的对象上调用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
}
计算路径中反斜杠的数量,并添加逻辑以选择第一级。也许是这样的?
$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}}
*已编辑为包括循环和符合要求的逻辑
我建议使用robocopy
而不是copy-item
。它的/LEV:n
开关听起来正是你想要的。示例(您需要进行测试和调整以满足您的要求):
robocopy $source $dest /LEV:2
robocopy
有大约7个选项,您可以指定这些选项来获得一些非常有用和有趣的行为。