Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Exclude directories in PowerShell

Tags:

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?

like image 926
svick Avatar asked Aug 08 '09 11:08

svick


People also ask

How to exclude directories in PowerShell?

To exclude directories, use the File parameter and omit the Directory parameter, or use the Attributes parameter. To get directories, use the Directory parameter, its "ad" alias, or the Directory attribute of the Attributes parameter.

What is recurse PowerShell?

-Recurse is a classic switch, which instructs PowerShell commands such as Get-ChildItem to repeat in sub directories. Once you remember that -Recurse comes directly after the directory, then it will serve you well in scripts that need to drill down to find information.


1 Answers

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.

PowerShell v3 finally has a -Directory parameter on Get-ChildItem:

Get-ChildItem -Directory gci -ad 
like image 90
Joey Avatar answered Oct 06 '22 08:10

Joey