我使用的是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
当前回答
在PowerShell 3.0中,它更简单:
Get-ChildItem -Directory #List only directories
Get-ChildItem -File #List only files
其他回答
在PowerShell 3.0中,它更简单:
Get-ChildItem -Directory #List only directories
Get-ChildItem -File #List only files
您可以尝试PsIsContainer对象
Get-ChildItem -path C:\mypath -Recurse | where {$_.PsIsContainer -eq $true}
这种方法需要更少的文本:
ls -r | ? {$_.mode -match "d"}
更干净的方法:
Get-ChildItem "<name_of_directory>" | where {$_.Attributes -match'Directory'}
我想知道PowerShell 3.0是否有一个只返回目录的开关;这似乎是一个合乎逻辑的补充。
公认的答案提到
Get-ChildItem -Recurse | ?{ $_.PSIsContainer } | Select-Object FullName
获取一个“原始字符串”。 但实际上select。system。io。directoryinfo类型的对象会被返回。对于原始字符串,可以使用以下方法:
Get-ChildItem -Recurse | ?{ $_.PSIsContainer } | % { $_.FullName }
如果该值连接到一个字符串,则区别很重要:
foo\@{FullName=bar} foreach操作符为预期的:foo\bar