将文件从源目录复制到目标目录,并从指定目录中排除特定文件类型

时间:2013-09-12 18:01:29

标签: file powershell directory copy

我创建了一个简单的Powershell脚本,用于在部署期间将文件从目标目录复制到源目录,我想排除文件列表。但需要注意的是,我希望能够仅在指定的情况下从子目录中排除文件。这是我用来执行复制并排除文件列表的片段:

$SourceDirectory = "C:\Source"
$DestinationDirectory = "C:\Destination"
$Exclude = @("*.txt*", "*.xml*") 

Get-ChildItem $SourceDirectory -Recurse -Exclude $Exclude | Copy-Item -Destination {Join-Path $DestinationDirectory $_.FullName.Substring($SourceDirectory.length)}

这将排除目录树中出现的指定文件。我想要使​​用排除列表的地方是这样的:

$Exclude = @("*Sub1\.txt*", "*.xml*").

这将仅在Sub1文件夹下排除.txt文件,而.xml文件将被排除在整个文件夹中。我知道这不起作用,但我希望它有助于更​​好地展示我正在努力解决的问题。

我考虑使用多维数组,但我不确定这是否有点过分。任何帮助将不胜感激。

2 个答案:

答案 0 :(得分:4)

这是一种方法

$SourceDirectory = 'C:\Source'
$DestinationDirectory = 'C:\Destination'
$ExcludeExtentions = '*.txt*', '*.xml*' 

$ExcludeSubDirectory = 'C:\Source\bad_directory1', 'C:\Source\bad_directory2'

Get-ChildItem $SourceDirectory -Recurse -Exclude $ExcludeExtentions | 
Where-Object { $ExcludeSubDirectory -notcontains $_.DirectoryName } |
Copy-Item -Destination $DestinationDirectory

这里最好的朋友是Where-Objectwhere。它将scriptblock作为参数,并使用该scriptblock验证通过管道的每个对象。只有使脚本返回$true的对象才能通过Where-Object传递。

另外,请查看代表您从Get-ChildItem获取的文件的对象。它已NameDirectoryDirectoryName分别包含已分割的文件FullNameDirectory实际上是表示父目录的对象,DirectoryName是字符串。 Get-Member命令行开关将帮助您发现隐藏的宝石,例如。

答案 1 :(得分:1)

$SourceDirectory =   'C:\Source'
$DestinationDirectory = 'C:\Destintation'
$ExcludeExtentions1 = "^(?=.*?(SubDirectory1))(?=.*?(.xml)).*$"
$ExcludeExtentions2 = "^(?=.*?(SubDirectory2))(?=.*?(.config)).*$"
$ExcludeExtentions3 = "^(?=.*?(.ps1))((?!SubDirectory1|SubDirectory2).)*$"
$ExcludeExtentions4 = ".txt|.datasource"

$files = Get-ChildItem $SourceDirectory -Recurse

foreach ($file in $files)
{
    if ($file.FullName -notmatch $ExcludeExtentions1 -and $file.FullName -notmatch $ExcludeExtentions2 -and $file.FullName -notmatch $ExcludeExtentions3-and $file.FullName -notmatch $ExcludeExtentions4)
    {
       $CopyPath = Join-Path $DestinationDirectory $file.FullName.Substring($SourceDirectory.length)
       Copy-Item $file.FullName -Destination $CopyPath
    }
}

在此解决方案中,使用regex和-notmatch,我可以从特定目录中排除特定文件类型。 $ ExcludeExtentions1将仅从SubDirectory1中排除xml文件,$ ExcludeExtentions2将仅从SubDirectory2排除配置文件,$ ExcludeExtentions3将排除ps1文件,只要它们不在两个子目录中的任何一个,$ ExcludeExtentions4将排除整个txt和数据源文件树。

我们实际上并没有在我们的解决方案中使用所有这些匹配,但是由于我正在研究这个问题,我想我会添加多个条件,以防其他人从这种方法中受益。

以下是一些也有帮助的链接: http://www.tjrobinson.net/?p=109 http://dominounlimited.blogspot.com/2007/09/using-regex-for-matching-multiple-words.html