Способ сделать это - проанализировать уровень вашего каталога по уровню: вы начинаете с списка каталогов, которые нужно проверить (изначально у вас есть только стартовая папка в списке). Затем для каждой папки в списке проверьте все прямые дочерние элементы: запишите файлы в файл результатов, добавьте папки в список «Следующие папки».
Сделайте это снова в списке «следующая папка», пока этот список не будет пустым.
Вы получите результат файл с файлом отсортированного по глубине (OK, глубокие файлы последние в файле, так что вам придется повернуть его вспять, но это сортируется по глубине в любом случае :)
Это можно сделать рекурсивно следующим образом:
function Parse-ByDepth ($dirs, $resultfile) {
[email protected]()
# if you also want the folders names in the result file
# write their names in the result file
$dirs |% {
echo "$_" >> $resultfile
}
# Parse each directory in the list
foreach ($dir in $dirs){
# note that the get-childitem here is non recursive.
# only one level is checked.
Get-ChildItem $dir | % {
if ($_.getType().Name -eq "FileInfo") {
# If the item is a file, append it to the result file
echo "$($_.FullName)" >> $resultfile
}else {
# if it is a folder, add the folder path to the "next folders" list
$nextdirs+=$_.FullName
}
}
}
# once all the item of the current level have been parsed, check if the list is empty
if ($nextdirs.Length -gt 0) {
# if the list contains more folder, parse them
Parse-ByDepth $nextdirs $resultfile
}
}
тогда, вы можете вызвать функцию таким образом:
[email protected]("d:\MyFolders")
$resultfile=C:\result_by_depth.txt
Parse-ByDepth $initdir $resultfile