【发布时间】:2019-07-22 16:30:08
【问题描述】:
'我正在尝试将多个文件从多个文件夹复制到另一个文件夹。文件夹中包含文件名的一部分。
例如—— 我想复制所有名称为“电话”或“单元”和序列号的文件作为文件名的一部分。每个子文件夹都有序列号作为文件夹名称的一部分。
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
【问题讨论】:
-
我创建了建议的文件结构和文件,运行它只会产生一个名为 Phones 的 0 KB 文件,在 C:\shared 没有类型
-
那么,完成后,您想要一个目标文件夹中所有文件的副本吗?也就是说,“C:\shared\112\products\112.phone blah blah.txt”将被复制到“C:\shared\112.phone blah blah.txt”,对吗?相反,如果我说您想要文件名中包含(“phone”或“Cell”)和(“112”或“113”)的所有文件,我是否正确?可能会更容易拉出整个文件夹,然后过滤掉您想要的内容(取决于实际标准的数量)。此外,它认为调用自身的函数形式不好。当操作系统试图跟踪每个调用时,它通常会导致堆栈溢出。
-
其实我希望它复制到“c:\shared\112.phone blah blah.txt” 你的第二个问题是肯定的。拉整个文件夹可能更容易,但每个序列号都有一个文件夹。
标签: shell powershell file copy