tags:

views:

671

answers:

3

I want to exclude all directories from my search in PowerShell. Both FileInfo and DirectoryInfo contain Attributtes property that seems to be exactly what I want, but I wasn't able to find out how to filter based on it. Both

ls | ? { $_.Attributes -ne 'Direcory' }
ls | ? { $_.Attributes -notcontains 'Direcory' }

didn't work. How can I do this?

+6  A: 

You can use the PSIsContainer property:

gci | ? { !$_.PSIsContainer }

Your approach would work as well, but would have to look like this:

gci | ? { !($_.Attributes -band [IO.FileAttributes]::Directory) }

as the attributes are an enum and a bitmask.

Or, for your other approach:

gci | ? { "$($_.Attributes)" -notmatch "Directory" }

This will cause the attributes to be converted to a string (which may look like "Directory, ReparsePoint"), and on a string you can use the -notmatch operator.

Joey
A: 

You can also filter out directories by looking at their type directly:

ls | ?{$_.GetType() -ne [System.IO.DirectoryInfo]}

Directories are returned by get-childitem (or ls or dir) of type System.IO.DirectoryInfo, and files are of type System.IO.FileInfo. When using the types as literals in Powershell you need to put them in brackets.

Anton I. Sipos
You can use the `-is` operator to do this, by the way. So it can be shortened to: `gci | ? {$_ -is [IO.FileInfo]}`
Joey
Of course you are limited to the File System Provider with this method whereas PsIsContainer should work with any provider where the concept of containers exists.
EBGreen
Should have thought of the -is operator. And yes, FileInfo will only work for File Systems.
Anton I. Sipos
A: 

I use

Get-ChildItem -include *.*

[edit] but it does not always work, apparently, (see comments) so use at your own risk. [edit]

The opposite is needed more often, though. (see http://stackoverflow.com/questions/1330648/powershell-analog-to-dir-ad-win-or-ls-d-bash/2526109#2526109)

Come to think about it, I do not really understand why it works...

buti-oxa
that doesn't do anything for me
svick
and if i do it the other way around (`-exclude *.*`), it lists also files without extension
svick
Hmm, it did work for fatcat1111 in the original question. Looks like there is a hidden setting that is different for different computers. PS version maybe? It would be nice to hear for an expert.
buti-oxa