我使用的是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

其他回答

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恰好产生两种类型的对象,而大多数命令只产生一种。

返回FileInfo和DirectoryInfo。

你可以通过查看该命令可用的“成员”来查看这一点,如下所示:

Get-ChildItem | Get-Member

TypeName: System.IO.DirectoryInfo TypeName: System.IO.FileInfo

您将看到每种类型可用的各种方法和属性。注意,这里有不同之处。例如FileInfo对象有一个length属性,而DirectoryInfo对象没有。

无论如何,从技术上讲,我们可以通过隔离DirectoryInfo对象只返回目录

Get-ChildItem | Where-Object {$_.GetType().Name -eq "DirectoryInfo"}

显然,正如上面的答案所述,最直接的解决方案是简单地使用Get-ChildItem -Directory,但我们现在知道如何在未来使用多种对象类型:)

PowerShell v2及更新版本(k表示您开始搜索的文件夹):

Get-ChildItem $Path -attributes D -Recurse

如果你只需要文件夹名,不需要其他任何东西,使用这个:

Get-ChildItem $Path -Name -attributes D -Recurse

如果您正在寻找特定的文件夹,您可以使用以下命令。在这种情况下,我正在寻找一个名为myFolder的文件夹:

Get-ChildItem $Path -attributes D -Recurse -include "myFolder"

首先需要使用get - childitem递归地获取所有文件夹和文件。然后将输出管道到只接收文件的Where-Object子句中。

# one of several ways to identify a file is using GetType() which
# will return "FileInfo" or "DirectoryInfo"
$files = Get-ChildItem E:\ -Recurse | Where-Object {$_.GetType().Name -eq "FileInfo"} ;

foreach ($file in $files) {
  echo $file.FullName ;
}

一个更易于阅读和简单的方法可以实现下面的脚本:

$Directory = "./"
Get-ChildItem $Directory -Recurse | % {
    if ($_.Attributes -eq "Directory") {
        Write-Host $_.FullName
    }
}

希望这能有所帮助!