【问题标题】:Copy-item exclude Sub-folders复制项目排除子文件夹
【发布时间】:2019-09-09 16:40:02
【问题描述】:

试图让我的复制项复制目录中除子文件夹之外的所有内容。我能够在文件夹和文件中排除,但不能在子文件夹中排除。

我尝试在复制项中使用 get-children 和 -exclude,但没有像我希望的那样排除它们


$exclude = "folder\common"

Get-ChildItem "c:\test" -Directory | 
    Where-Object{$_.Name -notin $exclude} | 
    Copy-Item -Destination 'C:\backup' -Recurse -Force

希望公用文件夹存在,但其中没有任何内容可以复制。

感谢您的帮助

【问题讨论】:

  • {$_.Name -notin $exclude} -> {$_.FullName -notmatch $exclude}
  • 试过了,但没有排除公用文件夹
  • $exclude 如果您使用正则表达式匹配(-match-notmatch),则需要进行正则表达式转义。 $exclude = [regex]::Escape("folder\common") 或手动转义 \ 与 \\.
  • @AdminOfThings 这两个我都试过了,好像没有排除文件夹
  • 如果 $exclude = "folder" 就容易多了。

标签: powershell powershell-3.0


【解决方案1】:

我认为这应该可以满足您的需求:

$sourceFolder = 'C:\test'
$destination  = 'C:\backup'
$exclude      = @("folder\common")  # add more folders to exclude if you like

# create a regex of the folders to exclude
# each folder will be Regex Escaped and joined together with the OR symbol '|'
$notThese = ($exclude | ForEach-Object { [Regex]::Escape($_) }) -join '|'

Get-ChildItem -Path $sourceFolder -Recurse -File | 
     Where-Object{ $_.DirectoryName -notmatch $notThese } | 
     ForEach-Object {
        $target = Join-Path -Path $destination -ChildPath $_.DirectoryName.Substring($sourceFolder.Length)
        if (!(Test-Path -Path $target -PathType Container)) {
            New-Item -Path $target -ItemType Directory | Out-Null
        }
        $_ | Copy-Item -Destination $target -Force
     }

希望有帮助

【讨论】:

  • 我确实从 .DirectoryName 切换到 .Fullname。对于某些我想要一个特定的文件名但进行微小更改的情况
  • 你说你可以添加更多文件夹来排除,语法是什么?
  • @Branderson20 只需将文件夹名称或文件夹路径位添加到 $exclude 数组。类似$exclude = "folder\common", "folder\notsocommon", "donttouchthisfolder"
  • 谢谢,是另一个问题,但解决了,谢谢
  • @glass_kites 你的意思是$target = Join-Path -Path $destination -ChildPath ('{0}_{1:yyyyMMddHHmmss}' -f $_.DirectoryName.Substring($sourceFolder.Length), (Get-Date))?当然。
【解决方案2】:

我认为在Get-ChildItem 上使用-exclude 参数会起作用:

$exclude = 'Exclude this folder','Exclude this folder 2','Folder3'

Get-ChildItem -Path "Get these folders" -Exclude $exclude | Copy-Item -Destination "Send folders here"

【讨论】:

    【解决方案3】:

    这是一个例子:

    $exclude= 'subfolderA'
    $path = 'c:\test'
    
    $fileslist = gci $path -Recurse
    
    foreach ($i in 0..$fileslist){  if( -not ($i.Fullname -like "*$($exlusion)*")){ copy-item -path $i.fullname -Destination 'C:\backup'  -Force  } }
    

    【讨论】:

    • 这对子文件夹不起作用,我想排除 folderA\subFolderA
    • 好吧,只是检查所有文件夹中的文件名,但如果需要更具体的话,可能会出现边缘情况
    • 这适用于排除文件夹中的所有子文件夹,因为“全名”包含父文件夹名称,因此排除。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-29
    相关资源
    最近更新 更多