0

Powershell script runs to add letter M in front of all file names. Then it continues to loop after the last file is modified and adds more MMMMs in front of the file name, in a loop. I need it to stop after the first run through all files in Directory.

I tried these three versions. The first with the space in front of M renames all files once but keeps the extra space in front of the name, if I can get rid of the space, it would be what I need:

DIR | Rename-Item -NewName {" M" + $_.BaseName + $_.Extension}

This version does not have the extra space in front of the M, but keeps adding MMMMs as long as the file name permits more characters.

DIR | Rename-Item -NewName {"M" + $_.BaseName + $_.Extension}

I also tried putting the letter as a parameter and using Foreach and got the same results as with just letter M in the first two versions:

$AL = "M"
Foreach-Object {
    DIR | Rename-Item -NewName {$AL + $_.BaseName + $_.Extension}
}

I need the files renamed with an M in front of the name, once and without the extra space. Thank you.

4
  • So, you want to add M to the start of the file name unless M is already the first character? Commented Jul 5, 2019 at 15:29
  • Try: DIR | ForEach-Object {Rename-Item -NewName ('M' + $_.BaseName + $_.Extension)} Commented Jul 5, 2019 at 15:32
  • 1
    @iRon - Your suggestion didn't work for me; while I suspected that it would have the same problem as Erinda's original attempts, it didn't; instead, it simply stopped and prompted me for the mandatory parameter Path to Rename-Item. DIR | ForEach-Object {Rename-Item -Path $_ -NewName ('M' + $_.BaseName + $_.Extension)} does work, however. Commented Jul 5, 2019 at 17:11
  • 1
    @iRon - I should note, however, that in both the corrected version of your solution and in my solution, the expression $_.BaseName + $_.Extension can be replaced by $_.Name. Commented Jul 5, 2019 at 17:13

1 Answer 1

2
$FileList = Get-ChildItem
$FileList | Rename-Item -NewName {"M" + $_.BaseName + $_.Extension}

Should do the trick. The difference between this and your original is that your original was getting a dynamic list of files; by storing the list of files in a variable, it becomes static, so that the already-renamed files aren't added to the list to be processed.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.