首页 > 解决方案 > 复制项目排除子文件夹

问题描述

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

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


$exclude = "folder\common"

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

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

谢谢您的帮助

标签: powershellpowershell-3.0

解决方案


我认为这应该做你需要的:

$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
     }

希望有帮助


推荐阅读