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

Get-ChildItem c:\mypath -Recurse

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

dir /b /ad /s

当前回答

Use:

dir -Directory -Recurse | Select FullName

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

其他回答

更干净的方法:

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

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

这个问题已经得到了很好的回答,但我想补充一些额外的东西,因为我刚刚看到了这个问题。

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,但我们现在知道如何在未来使用多种对象类型:)

Use:

Get-ChildItem \\myserver\myshare\myshare\ -Directory | Select-Object -Property name |  convertto-csv -NoTypeInformation  | Out-File c:\temp\mydirectorylist.csv

它执行以下操作

获取目标位置的目录列表: 获取\\myserver\myshare\myshare\ -目录 只提取目录的名称: 选择-对象-属性名 将输出转换为CSV格式: convertto-csv -NoTypeInformation 将结果保存到一个文件: Out-File c: \ temp \ mydirectorylist.csv

在PowerShell 3.0中,它更简单:

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

Use:

dir -r | where { $_ -is [System.IO.DirectoryInfo] }