复制项目排除子文件夹

时间:2019-09-09 16:40:02

标签: powershell powershell-3.0

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

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


$exclude = "folder\common"

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

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

感谢您的帮助

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
     }

希望有帮助

答案 1 :(得分:0)

这里是一个例子:

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

答案 2 :(得分:0)

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

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

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