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

Get-ChildItem c:\mypath -Recurse

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

dir /b /ad /s

当前回答

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

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

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

其他回答

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

对于PowerShell 3.0及更高版本:

Get-ChildItem -Directory

您还可以使用别名dir、ls和gci


对于低于3.0的PowerShell版本:

Get-ChildItem返回的FileInfo对象有一个“base”属性piscontainer。您只需要选择这些项。

Get-ChildItem -Recurse | ?{ $_.PSIsContainer }

如果您想要目录的原始字符串名称,您可以这样做

Get-ChildItem -Recurse | ?{ $_.PSIsContainer } | Select-Object FullName

具体回答原始问题(使用IO.FileAttributes):

Get-ChildItem c:\mypath -Recurse | Where-Object {$_.Attributes -band [IO.FileAttributes]::Directory}

但我更喜欢Marek的解决方案:

Where-Object { $_ -is [System.IO.DirectoryInfo] }

Use:

dir -Directory -Recurse | Select FullName

这将为您提供根结构的输出,其中仅包含目录的文件夹名称。

您可以尝试PsIsContainer对象

Get-ChildItem -path C:\mypath -Recurse | where {$_.PsIsContainer -eq $true}