Search code examples
powershellfile-rename

powershell remove last 3 characters from file name


I need to recursively rename a bunch of files with the extension '.cop' (for copy) and get rid of that '.cop' string.

I made the following command from what I read on the get-help rename-item topic:

gci -r -i *.cop | Rename-Item -newname {$_.name -replace '\.cop',''}

but I get an IO exception error :

Rename-Item : Cannot create a file when that file already exists.

PowerShell doesn't want to rename the file because it already exists? that doesn't make sense... anybody knows what I am doing wrong here ?

Thanks


Solution

  • You need to use the Foreach-Object Cmdlet:

    gci -r -i *.cop | % {ren $_ -newname $_.Name.Replace(".cop", "") -whatif}