File extension while searching

20,334

Solution 1

The $_.Extension will see the file as, (in the case of a text file) .txt

If $ext is currently a valid extension, then .$ext would look like ..txt echoed out.

The easiest way to get a list of files with a specific extension in PowerShell is one of two, really.

C like syntax:

$myList
Get-ChildItem |`
    Foreach-Object {
    if ($_.Extension -eq ".txt") { $myList += $_}
    }

PowerShell style:

Get-ChildItem | Where-Object {$_.Extension -eq ".txt"} | Do stuff

To get all files, as most files have an extension, just use Get-ChildItem or GCI or ls. (GCI and LS are aliases for Get-ChildItem).

To get all files with an extension, but not a specific extension:

Get-ChildItem | Where-Object {$_.Extension}

This evaluates as a bool, so true or false.

These are off the cuff, but should get you going in the right direction.

Solution 2

You can also use the -filter on Get-ChildItem:

Get-ChildItem -Filter "*.txt"

And you can specifiy recursion too:

Get-ChildItem -Recurse -Filter "*.txt"

Share:
20,334
pawel__86
Author by

pawel__86

Updated on July 09, 2022

Comments

  • pawel__86
    pawel__86 almost 2 years

    I am trying to get a list of all my files with a specific extension.

    (...)$_.Extension -eq ".$ext"
    

    I read extension from console to script.

    My question is how to find any file with an extension of .*?

    Edit:

    Here's the rest of the code:

    $setOfFolders = (Get-ChildItem -Path D:\ -Directory).name 
    Write-host "Set last write date " -ForegroundColor Yellow -NoNewline 
    $ostZmiana= read-host $exten = read-host "Set extensions " 
    
    ForEach ($f in $setOfFolders) 
    { 
        $saveTofile = "C:\Users\pziolkowski\Desktop\Outs\$f.txt" 
        Get-ChildItem -Path D:\Urzad\Wspolny\$f -Recurse | ? {$_.LastAccessTime -lt $ostZmiana -and $_.Extension -eq ".$exten"} | % {Get-acl $_.FullName} |sort Owner | ft -AutoSize -Wrap Owner, @{Label="ShortPath"; Expression= $_.Path.Substring(38)}} > $saveToFile 
    }
    
  • pawel__86
    pawel__86 over 10 years
    Thanks :) but you said how to find specyfic extension but I nedd any (like file.log and file.jpg) file.*
  • Austin T French
    Austin T French over 10 years
    Update your question then, I will update the answer. Currently you start with Im trying to get list of files with specific extension.
  • DarkLite1
    DarkLite1 over 8 years
    After testing it appears that for filtering file extensions -Filter "*.txt" is a lot faster than -Include *.txt. Thanks for the tip!
  • TTT
    TTT about 3 years
    This doesn't actually match the extension. It also matches "Filename.txt-skip" !