我使用的是PowerShell 2.0,我想输出某个路径的所有子目录。下面的命令输出所有文件和目录,但我不知道如何过滤掉这些文件。

Get-ChildItem c:\mypath -Recurse

我尝试使用$_。属性来获取属性,但我不知道如何构造System.IO.FileAttributes的字面实例来进行比较。在cmd.exe中就是这样

dir /b /ad /s

当前回答

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

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

希望这能有所帮助!

其他回答

我的解决方案是基于TechNet文章Get-ChildItem Cmdlet可以做的有趣的事情。

Get-ChildItem C:\foo | Where-Object {$_.mode -match "d"}

我在我的剧本中使用了它,效果很好。

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"

在PowerShell 3.0中,它更简单:

Get-ChildItem -Directory #List only directories
Get-ChildItem -File #List only files

更干净的方法:

Get-ChildItem "<name_of_directory>" | where {$_.Attributes -match'Directory'}

我想知道PowerShell 3.0是否有一个只返回目录的开关;这似乎是一个合乎逻辑的补充。

首先需要使用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 ;
}