Search code examples
powershellsubstringfile-rename

Remove substring from fileanme using Powershell command or script


I know this is very basic and it has been discussed @ multiple places but still I could not find my answer so I am starting a new thread here.

I've started using powershell and I need to write a script to remove substring from filename. For example I have below file names -

TevarMadamiyan.txt
TevarLetsCelebrate.txt
TevarMMsdfORO.txt
TevarSupper.txt

The thing is, I need to remove initial part of filename called "Tever" from all files. How do I do that ?

So far I've tried below method but its not working because new file name becomes empty string -

Get-ChildItem | Rename-Item -NewName {$_.Name -replace "Tever.*",""}

Solution

  • you have a typo in Tever...anyway the .* will match the whole string which is not what you want. Also you want to perform the rename operation on the basename rather than the name.

    The -whatif will show you the result without actually performing the rename.

    Get-ChildItem -Path yourpath -Filter Tevar*.txt | 
      Rename-Item -NewName { ($_.basename -replace 'Tevar') + $_.Extension} -WhatIf