Slowstuff
Slowstuff

Reputation: 109

How to select files that have no extension using powershell

I have a drive with lots of directories and files, some of which are broken and have no file extension. I would like to delete all of the files that do NOT have an extension. I have tried gci | where {$_.extension -eq ""} and gci | where {$_.extension -eq "."} and variations of those, but end up getting nothing or everything on the drive.

If I look at the results of gci | select Extension the files show nothing for the extension, just like a directory, not sure where to go.

Any help would be appreciated.

Upvotes: 5

Views: 5462

Answers (4)

js2010
js2010

Reputation: 27443

Or

get-childitem * -file -exclude *.*

or

get-childitem -file | ? extension -eq '' # not $null or $false

I wish I could say | ? ! extension, although you can say | ? { ! $_.extension }.

Upvotes: 0

mklement0
mklement0

Reputation: 437998

The simplest and fastest solution (PSv3+) is to use the -Filter parameter:

Get-ChildItem -File -Filter *.

as explained in this answer.

As for a pipeline-based solution:

PowerShell (Core) 7 now offers the -Not switch with the simplified comparison statement syntax that itself was introduced to Where-Object (whose built-in alias is ?) in Windows PowerShell v3, which enables the following, more concise variant of TheMadTechnician's helpful answer:

Get-ChildItem -File | Where-Object -Not Extension

# Alternatively, using built-in alias ? for Where-Object
Get-ChildItem -File | ? -Not Extension

As in TheMadTechnician's answer, this uses implicit Boolean logic: any nonempty string evaluates to $True in a Boolean context, so applying -Not (whose alternative form in expression(-parsing) mode is !) means that $true is only returned if the string is empty, i.e., if the file has no extension.


As for what you tried:

gci | where {$_.extension -eq ""} works in principle, except that it also includes directories.

In PSv3+ you can use the -File switch to limit the results to files, as above.

In PSv2 you must add a condition to the script block, based on the .PSISContainer property only returning $True for directories:

gci | where { -not $_.PSIsContainer -and $_.Extension -eq "" }

Upvotes: 9

TheMadTechnician
TheMadTechnician

Reputation: 36297

gci -File -Recurse | ?{!($_.Extension)}

Upvotes: 11

Lee
Lee

Reputation: 144136

ls | where {!$_.PsIsContainer -and ![io.path]::hasextension($_.name) }

Upvotes: 2

Related Questions