Erinda
Erinda

Reputation: 3

How to end powershell script after the last file in dir

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.

Upvotes: 0

Views: 79

Answers (1)

Jeff Zeitlin
Jeff Zeitlin

Reputation: 10799

$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.

Upvotes: 2

Related Questions