Beginner_Scripter
Beginner_Scripter

Reputation: 15

Using PowerShell to remove file extension

I'm trying to clean up some folders in Windows that have dozens of text files with a double .txt extension. (file1.txt.txt) I thought the PowerShell script below would work, but it's giving me errors.

Get-ChildItem -Filter *.txt -Recurse -File -Name | ForEach-Object {Rename-Item $_.BaseName}

Rename-Item : Cannot bind argument to parameter 'Path' because it is null. At line:1 char:80

Based on the error saying the Path is null, I added "-Path .\ " to the command but it returns the same error message.

I've looked at the following post, but the suggestions shown are not working for me. Removing path and extension from filename in PowerShell

Get-ChildItem -Filter *.txt -Recurse -File -Name | ForEach-Object {Rename-Item $_.BaseName}

Rename-Item : Cannot bind argument to parameter 'Path' because it is null. At line:1 char:80

Based on the error saying the Path is null, I added "-Path .\ " to the command but it returns the same error message.

Upvotes: 0

Views: 278

Answers (1)

Santiago Squarzon
Santiago Squarzon

Reputation: 60848

The error is because -Name makes Get-ChildItem output a string and strings have no .BaseName property, thus when you do $_.BaseName it defaults to null and you get that error.

Aside from that, considering you didn't want to output only the file's Name, you would still be missing an argument for Rename-Item (the -NewName).

What you most likely wanted to do is:

Get-ChildItem -Filter *.txt -Recurse -File | ForEach-Object { Rename-Item $_.FullName -NewName $_.BaseName }

However there is a more simplified version using a delay-bind script block:

Get-ChildItem -Filter *.txt -Recurse -File | Rename-Item -NewName { $_.BaseName }

You should also consider using -Filter *.txt.txt so as to only rename files that have doubled extension.

Upvotes: 2

Related Questions