Powershell从源目录中复制特定文件,不包括几个文件夹,但随后使用通配符递归文件



这是我当前的脚本,它运行良好。运行两次相同的代码效率不高,但我不知道如何组合通配符。。。不管怎样,还是转到更大的问题上。

下面的代码搜索我的$sourceDir,排除$ExclusionFiles中列出的文件,复制所有文件夹和结构以及任何.jpg或任何.csv文件,然后将它们放入$targetDir中。

$sourceDir = 'c:sectionOneGraphicsData'
$targetDir = 'C:Test'
$ExclusionFiles = @("InProgress.jpg", "input.csv", "PCMCSV2.csv")
# Get .jpg files
Get-ChildItem $sourceDir -filter "*.jpg" -recurse -Exclude $ExclusionFiles | `
foreach{
$targetFile = $targetDir + $_.FullName.SubString($sourceDir.Length);
New-Item -ItemType File -Path $targetFile -Force;
Copy-Item $_.FullName -destination $targetFile
}
# Get .csv files
Get-ChildItem $sourceDir -filter "*.csv" -recurse -Exclude $ExclusionFiles | `
foreach{
$targetFile = $targetDir + $_.FullName.SubString($sourceDir.Length);
New-Item -ItemType File -Path $targetFile -Force;
Copy-Item $_.FullName -destination $targetFile
}

我需要排除的主$sourceDir中的文件列表越来越长,而且还有一些文件夹我也要排除。有人能告诉我怎么做吗,

  • 仅复制$sourceDir中特定文件的列表
  • 从复制中排除$sourceDir中的某些文件夹
  • 将.jpg和.csv的通配符搜索合并为一条语句

我仍在学习,如果有任何帮助,我们将不胜感激!

在这种情况下,一点Regex会有很大的帮助:

您可以使用一个非常基本的匹配来过滤多个扩展:

$extensions = 'jpg', 'csv'
$endsWithExtension = ".(?>$($extensions -join '|'))$"
Get-ChildItem -Recurse |
Where-Object Name -Match $endsWithExtension

您可以通过一个Where Object和-In参数排除特定文件的列表:

$extensions = 'jpg', 'csv'
$endsWithExtension = ".(?>$($extensions -join '|'))$"
$ExcludeFileNames = @("InProgress.jpg", "input.csv", "PCMCSV2.csv")
Get-ChildItem -Recurse |
Where-Object Name -Match $endsWithExtension |
Where-Object Name -NotIn $ExcludeFileNames

从中开始,你的Foreach对象基本上是正确的(通过使用New Item来确保文件存在,尽管我个人会将其输出指定为null并通过复制项(。

Get-ChildItem $sourceDir -Recurse |
Where-Object Name -Match $endsWithExtension |
Where-Object Name -NotIn $ExcludeFileNames | 
Foreach-Object {
$targetFile = $targetDir + $_.FullName.SubString($sourceDir.Length);
New-Item -ItemType File -Path $targetFile -Force;
Copy-Item $_.FullName -destination $targetFile
}

最新更新