Powershell 如何将子项从最深的子文件夹排序到最高的子文件夹?
我尝试通过执行以下操作来获取文件夹的文件及其子文件夹中的文件: $files=获取子项“d:\MyFolders”-递归 问题: 如何按文件夹层次结构对$文件进行排序,这意味着最深的文件将位于数组的顶部,而最上面的文件将是最后一个元素Powershell 如何将子项从最深的子文件夹排序到最高的子文件夹?,powershell,powershell-3.0,Powershell,Powershell 3.0,我尝试通过执行以下操作来获取文件夹的文件及其子文件夹中的文件: $files=获取子项“d:\MyFolders”-递归 问题: 如何按文件夹层次结构对$文件进行排序,这意味着最深的文件将位于数组的顶部,而最上面的文件将是最后一个元素 注:原因是如果我重命名一些文件夹,那么这些重命名文件夹下的文件路径将无效。因此,我想先处理最深的文件夹,然后移到上面的文件。它没有按深度进行专门排序,但由于排序的原因,它会将同一父文件夹中的文件夹分组在一起 $files | Sort-Object -Descen
注:原因是如果我重命名一些文件夹,那么这些重命名文件夹下的文件路径将无效。因此,我想先处理最深的文件夹,然后移到上面的文件。它没有按深度进行专门排序,但由于排序的原因,它会将同一父文件夹中的文件夹分组在一起
$files | Sort-Object -Descending FullName | Select-Object FullName
如果确实需要按文件夹深度排序,可以这样做:
$files | Select-Object FullName, @{Name="FolderDepth";Expression={$_.DirectoryName.Split('\').Count}} | Sort-Object -Descending FolderDepth,FullName
如果要反转排序,只需删除-降序即可。一种方法是逐级解析目录:从要检查的目录列表开始(最初,列表中只有开始文件夹)。
$files | Sort-Object -Descending FullName | Select-Object FullName
然后,对于列表中的每个文件夹,检查所有直接子文件夹:将文件写入结果文件,将文件夹添加到“下一个文件夹”列表中
使用“下一个文件夹”列表再次执行此操作,直到此列表为空
您将得到一个按深度排序的结果文件(好的,最深的文件是文件中的最后一个,因此您必须将其反转,但它仍然按深度排序:)
这可以通过以下方式递归完成:
function Parse-ByDepth ($dirs, $resultfile) {
$nextdirs=@()
# 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
}
}
$initdir=@("d:\MyFolders")
$resultfile=C:\result_by_depth.txt
Parse-ByDepth $initdir $resultfile
然后,可以通过以下方式调用该函数:
function Parse-ByDepth ($dirs, $resultfile) {
$nextdirs=@()
# 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
}
}
$initdir=@("d:\MyFolders")
$resultfile=C:\result_by_depth.txt
Parse-ByDepth $initdir $resultfile