复制项目排除子文件夹

Copy-item exclude Sub-folders

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

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


$exclude = "folder\common"

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

希望公共文件夹存在,但不会复制其中的任何内容。

感谢帮助

这是一个例子:

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

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

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

希望对您有所帮助

我认为在 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"