'我正在尝试将多个文件从多个文件夹复制到另一个文件夹。这些文件夹中有一部分文件名。
例如- 我想复制所有名称为“ Phone”或“ cell”且序列号作为文件名一部分的文件。每个子文件夹都有序列号作为文件夹名称的一部分。
C:\shared\112\products\112.phone blah blah.txt
C:\shared\112\products\112.my cell.txt
C:\shared\113\products\113.ugly phone.txt
C:\shared\113\products\113.the cell.txt
C:\shared\114\products\114.pretty phone.txt
C:\shared\115\products\115.phone lazy.txt
C:\shared\115\products\115.celly cell.txt
问题是有20,000个序列号,所以我想设置一个序列号列表并根据一组序列号提取文件。 这是我的脚本,但是它什么也没拉。'
$FirstSearchlist = @(“112”, “113”)
$SecondSearchlist = @("phone","cell")
$dirArray = @("c:\Shared\")
$NotFound = "Not Found"
cls
function Recurse([string]$path) {
$fc = new-object -com scripting.filesystemobject
$folder = $fc.getfolder($path)
foreach ($i in $folder.files) {
[string]$FullPath = $i.Path
[string]$FileName = $i.Name
foreach($first in $FirstSearchlist) {
if ($filename.ToUpper().Contains($first.ToUpper())) {
foreach($second in $SecondSearchlist) {
if ($filename.ToUpper().Contains($second.ToUpper())) {
Write-Host $Fullpath
Copy-Item $Fullpath -Destination "C:\Shared\Phones" -Recurse
}
}
}
}
}
foreach ($i in $folder.subfolders) {
Recurse($i.path)
}
}
function main() {
foreach ($i in $FirstSearchlist){
$NewFolder = $dirArray + $i
foreach($SearchPath in $NewFolder) {
Recurse $SearchPath
}
}
}
main
答案 0 :(得分:0)
这对于我使用提供的示例集进行测试有效(但请注意,我的测试C:\ Shared为空,可能要根据您的需要调整文件夹树):
Function Get-FileMatches($Filter){
$fileMatches = Get-ChildItem -Path "C:\Shared" -Recurse | ? {$_.Mode -notmatch 'd' -and $_.Name -match $Filter -and ($_.Name -match $SecondSearchlist[0] -or $_.Name -match $SecondSearchlist[1])}
return $fileMatches
}
Function Run-Script() {
$FirstSearchlist = @(“112”, “113”)
$SecondSearchlist = @("phone","cell")
$allMatches = @()
$phonesFolderExists = Test-Path "C:\Shared\Phones"
if($phonesFolderExists -eq $False)
{
New-Item -Path "C:\Shared\Phones" -ItemType Directory -Force
}
foreach($listItem in $FirstSearchList) {
$currentMatches = Get-FileMatches -Filter $listItem
if($currentMatches -ne $null)
{
foreach($item in $currentMatches)
{
$allMatches += $item
}
}
}
if($allMatches -ne $null)
{
foreach($item in $allMatches)
{
Copy-Item -Path $item.FullName -Destination "C:\Shared\Phones"
}
}
}
Run-Script