使用PowerShell进行复制时排除多个文件夹

时间:2017-07-26 05:29:54

标签: powershell get-childitem copy-item

目标是使用PowerShell将文件夹和文件从路径复制到另一个路径。但是,我想排除某些文件和文件夹被复制。我可以通过将多个文件添加到排除列表

来排除多个文件
$directory = @("Bin")
?{$_.fullname -notmatch $directory}

为了排除我添加的文件夹

Get-ChildItem -Path $source -Recurse -Exclude "Web.config","body.css","Thumbs.db" | ?{$_.fullname -notmatch $directory} | Copy-Item -Force -Destination {if ($_.GetType() -eq [System.IO.FileInfo]) {Join-Path $dest $_.FullName.Substring($source.length)} else {Join-Path $dest $_.Parent.FullName.Substring($source.length)}}

,最终的副本脚本看起来像

{{1}}

这似乎适用于单个文件夹,但是当我向排除目录添加多个文件夹时,它似乎无法正常工作。可以做些什么来排除多个文件夹?

3 个答案:

答案 0 :(得分:1)

$source = 'source path'
$dest = 'destination path' 
[string[]]$Excludes = @('file1','file2','folder1','folder2')
$files =  Get-ChildItem -Path $source -Exclude $Excludes | %{ 
$allowed = $true
foreach ($exclude in $Excludes) { 
    if ((Split-Path $_.FullName -Parent) -match $exclude) { 
        $allowed = $false
        break
    }
}
if ($allowed) {
    $_.FullName
}
}
copy-item $source $dest -force -recurse 

上述代码不包括$ Excludes数组中列出的多个文件夹,并将剩余内容复制到目标文件夹

答案 1 :(得分:0)

因为$directory是一个数组,所以你应该寻找匹配它的内容而不是它本身(令人讨厌的是powershell允许单元素数组被视为它们的内容)。

您可以尝试:

?{$directory -contains $_.fullname}

而不是:

?{$_.fullname -notmatch $directory}

答案 2 :(得分:0)

试试这个:

$excluded = @("Web.config", "body.css","Thumbs.db")
Get-ChildItem -Path $source -Recurse -Exclude $excluded

从评论中,如果您要排除文件夹,可以使用以下内容:

Get-ChildItem -Path $source -Directory -Recurse  | 
      ? { $_.FullName -inotmatch 'foldername' }

或者您可以先检查容器然后执行此操作:

Get-ChildItem -Path $source -Recurse  | 
      ? { $_.PsIsContainer -and $_.FullName -notmatch 'foldername' }