我使用的是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
当前回答
具体回答原始问题(使用IO.FileAttributes):
Get-ChildItem c:\mypath -Recurse | Where-Object {$_.Attributes -band [IO.FileAttributes]::Directory}
但我更喜欢Marek的解决方案:
Where-Object { $_ -is [System.IO.DirectoryInfo] }
其他回答
这种方法需要更少的文本:
ls -r | ? {$_.mode -match "d"}
Use:
dir -r | where { $_ -is [System.IO.DirectoryInfo] }
用这个吧:
Get-ChildItem -Path \\server\share\folder\ -Recurse -Force | where {$_.Attributes -like '*Directory*'} | Export-Csv -Path C:\Temp\Export.csv -Encoding "Unicode" -Delimiter ";"
我的解决方案是基于TechNet文章Get-ChildItem Cmdlet可以做的有趣的事情。
Get-ChildItem C:\foo | Where-Object {$_.mode -match "d"}
我在我的剧本中使用了它,效果很好。
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