gpt4 book ai didi

powershell - 目录列表递归父子内

转载 作者:行者123 更新时间:2023-12-05 03:23:26 24 4
gpt4 key购买 nike

我想使用 -recurse 获取目录列表,但要显示父目录下的子目录。

这是我尝试过的:

Get-ChildItem -Directory -Depth 3 | Select-Object Fullname

结果首先显示顶级目录,然后是 2 级目录,然后是 3 级目录

例子:

C:\Users\Moshe\onedrive\pictures\35mm_Film    (has no sub directories)
C:\Users\Moshe\onedrive\pictures\Camera imports
C:\Users\Moshe\onedrive\pictures\Camera Roll

只有那时

C:\Users\Moshe\onedrive\pictures\Camera imports\Folder1
C:\Users\Moshe\onedrive\pictures\Camera imports\Folder2
C:\Users\Moshe\onedrive\pictures\Camera imports\Folder3

然后

C:\Users\Moshe\onedrive\pictures\Camera Roll\2014
C:\Users\Moshe\onedrive\pictures\Camera Roll\2016

我想得到显示父目录和子目录正下方的列表

例如:

C:\Users\Moshe\onedrive\pictures\35mm_Film    (has no sub directories)
C:\Users\Moshe\onedrive\pictures\Camera imports
C:\Users\Moshe\onedrive\pictures\Camera imports\Folder1
C:\Users\Moshe\onedrive\pictures\Camera imports\Folder2
C:\Users\Moshe\onedrive\pictures\Camera imports\Folder3
C:\Users\Moshe\onedrive\pictures\Camera Roll
C:\Users\Moshe\onedrive\pictures\Camera Roll\2014
C:\Users\Moshe\onedrive\pictures\Camera Roll\2016

每个目录的文件数也很好,但不重要

例如:

C:\Users\Moshe\onedrive\pictures\35mm_Film 100
C:\Users\Moshe\onedrive\pictures\Camera imports 0 (no files in the parent)
C:\Users\Moshe\onedrive\pictures\Camera imports\Folder1 20

等等

最佳答案

如果您想在不需要事后排序的情况下执行此操作,解决方案可能会有点麻烦,您可以使用递归 function/script block或者如本例所示,使用 Stack<T> 作为可选,您可以使用 class :

class Tree {
[int] $Depth
[string] $Path
[int] $FileCount
hidden [IO.DirectoryInfo] $Instance

Tree ([IO.DirectoryInfo] $Directory, [int] $Depth) {
$this.Instance = $Directory
$this.Path = $Directory.FullName
$this.Depth = $Depth
$this.CountFiles()
}

[IO.DirectoryInfo[]] EnumerateDirectories() {
return $this.Instance.EnumerateDirectories()
}

[void] CountFiles() {
$this.FileCount = $this.Instance.GetFiles().Count
}
}


$stack = [Collections.Generic.Stack[Tree]]::new()
# define max Depth here
$maxDepth = 3
# initial path here
$path = 'C:\Users\Moshe\onedrive\pictures'
# define what you want to skip here
$attrToSkip = [IO.FileAttributes] 'Hidden'
$stack.Push([Tree]::new($path, 0))

while($stack.Count) {
$folder = $stack.Pop()

# this conditions stops the loop
$reachedMaxDepth = $folder.Depth -gt $maxDepth
# this condition skips Hidden folders, remove it if you want to show all
$isHiddenorSystem = $folder.Instance.Attributes -band $attrToSkip

if($reachedMaxDepth -or $isHiddenorSystem) {
continue
}

$folder

foreach($i in $folder.EnumerateDirectories()) {
$stack.Push([Tree]::new($i, $folder.Depth + 1))
}
}

关于powershell - 目录列表递归父子内,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72525159/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com