Get list of files without extension in powersehll

Spunny 366 Reputation points
2022-03-31T21:05:32.9+00:00

Hi,
We get files like this from vendor

aaa.bbb.dat
xxxYYY
dddd.eee
zzzzz.dat
ffff.txt

I need to get all the files without extension (in this example xxxYYY and dddd.eee) and add .dat extension to them.
After I add extension, files should look like this in the folder:
aaa.bbb.dat
xxxYYY.dat
dddd.eee.dat
zzzzz.dat
ffff.txt

The code I tried:

$files = Get-ChildItem "\\rootfolder\reports"

********************* STE2: Loop through all the files and check for .dat extension. If there is no extension, add extension to the file

foreach ($f in $files){
    $outfile = $f.FullName 
    $fileName = $f.Name

    if ($fileName -Like "*.dat")
    {
          #do nothing

    } 
    else
    {
        $newName = $fileName + ".dat"        
        Rename-Item -Path $outfile -NewName $newName

    }      

} # end of for loop

I don't like this code because if there is file with .txt extension, it adds .dat to the file. Any other way of getting only list of files that don't have extension and then add .dat.
I don't want to limit my filter criteria to .dat or .txt if I can.

In my logic I should get only files that don't have extension and add .dat to them.

Thank You

Windows for business | Windows Server | User experience | PowerShell
0 comments No comments
{count} votes

Accepted answer
  1. MotoX80 36,401 Reputation points
    2022-03-31T22:31:23.21+00:00

    For files that do not have an extension, it's pretty easy. For files with an extension, like ".eee", you'll have to determine if this is a known extension that can be ignored, or something else where you want to append ".dat".

    Here's one way.

    $ignore = @('.txt','.log','.dat','.ps1' ,'.bat','.zip')   
    Get-ChildItem -Path c:\temp -File  | foreach {
        ""
        $_.Name
        if ($ignore -contains $_.Extension ) {
            # Leave it alone 
        } else {
            $newname = $_.name + ".dat"
            "rename to $newname"
        }
    }
    

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.