我使用的是PowerShell 2.0,我想输出某个路径的所有子目录。下面的命令输出所有文件和目录,但我不知道如何过滤掉这些文件。
Get-ChildItem c:\mypath -Recurse
我尝试使用$_。属性来获取属性,但我不知道如何构造System.IO.FileAttributes的字面实例来进行比较。在cmd.exe中就是这样
dir /b /ad /s
我使用的是PowerShell 2.0,我想输出某个路径的所有子目录。下面的命令输出所有文件和目录,但我不知道如何过滤掉这些文件。
Get-ChildItem c:\mypath -Recurse
我尝试使用$_。属性来获取属性,但我不知道如何构造System.IO.FileAttributes的字面实例来进行比较。在cmd.exe中就是这样
dir /b /ad /s
当前回答
Use
Get-ChildItem -dir #lists only directories
Get-ChildItem -file #lists only files
如果您更喜欢别名,请使用
ls -dir #lists only directories
ls -file #lists only files
or
dir -dir #lists only directories
dir -file #lists only files
要递归子目录,添加-r选项。
ls -dir -r #lists only directories recursively
ls -file -r #lists only files recursively
在PowerShell 4.0、PowerShell 5.0 (Windows 10)、PowerShell Core 6.0 (Windows 10、Mac和Linux)和PowerShell 7.0 (Windows 10、Mac和Linux)上进行测试。
注意:在PowerShell Core上,指定-r开关时不遵循符号链接。要跟随符号链接,请使用-r指定-FollowSymlink开关。
注2:PowerShell现在是跨平台的,从版本6.0开始。跨平台版本最初被称为PowerShell Core,但自PowerShell 7.0+以来,“Core”一词已被删除。
Get-ChildItem文档:https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.management/get-childitem
其他回答
在PowerShell 3.0中,它更简单:
Get-ChildItem -Directory #List only directories
Get-ChildItem -File #List only files
Use
Get-ChildItem -dir #lists only directories
Get-ChildItem -file #lists only files
如果您更喜欢别名,请使用
ls -dir #lists only directories
ls -file #lists only files
or
dir -dir #lists only directories
dir -file #lists only files
要递归子目录,添加-r选项。
ls -dir -r #lists only directories recursively
ls -file -r #lists only files recursively
在PowerShell 4.0、PowerShell 5.0 (Windows 10)、PowerShell Core 6.0 (Windows 10、Mac和Linux)和PowerShell 7.0 (Windows 10、Mac和Linux)上进行测试。
注意:在PowerShell Core上,指定-r开关时不遵循符号链接。要跟随符号链接,请使用-r指定-FollowSymlink开关。
注2:PowerShell现在是跨平台的,从版本6.0开始。跨平台版本最初被称为PowerShell Core,但自PowerShell 7.0+以来,“Core”一词已被删除。
Get-ChildItem文档:https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.management/get-childitem
更干净的方法:
Get-ChildItem "<name_of_directory>" | where {$_.Attributes -match'Directory'}
我想知道PowerShell 3.0是否有一个只返回目录的开关;这似乎是一个合乎逻辑的补充。
我的解决方案是基于TechNet文章Get-ChildItem Cmdlet可以做的有趣的事情。
Get-ChildItem C:\foo | Where-Object {$_.mode -match "d"}
我在我的剧本中使用了它,效果很好。
Use:
dir -Directory -Recurse | Select FullName
这将为您提供根结构的输出,其中仅包含目录的文件夹名称。