0
votes

I'm trying to tidy up a batch of filenames using Powershell and I'm getting this error:

Rename-Item : Cannot create a file when that file already exists.
At line:1 char:7
+ Dir | Rename-Item -NewName {$_.Name.Substring(0,$_.BaseName.Length-4) ...
+       ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : WriteError: (C:\Users\garet\...e Mine (1).mp3:String) [Rename-Item], IOException
    + FullyQualifiedErrorId : RenameItemIOError,Microsoft.PowerShell.Commands.RenameItemCommand

The command I'm using is:

Dir | Rename-Item -NewName {$_.Name.Substring(0,$_.BaseName.Length-4) + $_.Extension}
1
Add -WhatIf switch to the rename command to see what kind of file names you'll get.vonPryz

1 Answers

2
votes

I think your command isn't removing the first 4 characters at the moment, but rather the last 4 characters. Try this:

Dir | Rename-Item -NewName {$_.name.substring(4,$_.BaseName.length-4) + $_.Extension}

You can simplify this further as if you want the full length of a string less a number of characters at the start you can just provide the starting index.

Dir | Rename-Item -NewName {$_.name.substring(4) + $_.Extension}

For example:

'test'.substring(2)

Outputs:

st

Explanation:

When using substring you pass two values, the first is the character index of the string you want to start from, the second is how many characters of the string from that point you want to capture.