1

I would like to remove the word “.pdf” in the file name. It’s not the extension of the file as I named it with “.pdf” previously. How do I remove it on all of the files? My files are located in many folders within the main folder.

C:\MainFolder\Folder1\document.pdf

C:\MainFolder\Folder2\document

C:\MainFolder\Folder3\document.pdf

Get-ChildItem | Rename-Item -NewName { $_.BaseName.Replace(“.pdf”,””) + $_.Extension }

I tried using this but it only removes in the folder itself. I need to do it for all of the folders

Community
  • 1
  • 1
Kimber Ker
  • 29
  • 6
  • 2
    I have not seen your piece of code and the folder structure and sample file names. Please edit the question and share the same. Also, based on my assumption, I am giving an answer. – Ranadip Dutta Oct 23 '19 at 08:33
  • Please do not delete and re-post the exact same question. Edit and improve your existing question to avoid loosing all clarification already discussed in the comments. – Filburt Oct 23 '19 at 08:35
  • 2
    Just add the `-Recurse` option to [Get-ChildItem](https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.management/get-childitem?view=powershell-6) to scan all subfolders. – Filburt Oct 23 '19 at 08:42

3 Answers3

1

This should do the trick:

    $files = Get-ChildItem 'C:\mypath' -Recurse

    foreach( $file in $files ) {

    if( !$file.PSIsContainer ) {

        $extension = $file.Extension
        $newname   = $file.BaseName.Replace('.pdf', '' ) + $extension
        Rename-Item -Path $file.FullName -NewName $newname | Out-Null
    }

}
f6a4
  • 1,684
  • 1
  • 10
  • 13
0

Replace your piece of code with this:

#Finds all files with the string “pdf” anywhere in the name recursively and will replace with nothing(which will remove basically).
Get-ChildItem -Path C:\your\root\folder\path -Filter "*pdf*" -Recurse  | Rename-Item -NewName {$_.Name -replace "pdf",''}

Hope it helps.

Ranadip Dutta
  • 8,857
  • 3
  • 29
  • 45
0

As Filburt points out in a comment on the question, the only thing missing from your command is the -Recurse switch in order to process files in the entire directory subtree of the input path.

Additionally, to be safe, add the -File switch in order to limit processing to files (and not also directories):

Get-ChildItem -Recurse -File |
  Rename-Item -NewName { $_.BaseName.Replace('.pdf', '') + $_.Extension } -WhatIf

The -WhatIf common parameter previews the operation. Remove it once you're sure it will do what you want.

Note that files whose base names do not contain the substring .pdf are effectively ignored.

To speed up processing, you could make Get-ChildItem preselect the files of interest with
-Filter *.pdf?*

mklement0
  • 382,024
  • 64
  • 607
  • 775