-1

I’m trying to make a script that removes the ” – Shortcut” from shortcut names and have discovered an odd phenomenon, if the name is under 6 characters not including the “ – Shortcut.lnk” the loop goes through an extra cycle for that file and makes its name blank. However this only applies to the first file not any file after the first.

So if we have two lnk files one is “12345 – Shortcut.lnk” and the other is “C1 – Shortcut.lnk” the output is a blank lnk file and a “C1.lnk”

But “123456 – Shortcut.lnk” and “C1 – Shortcut.lnk” gives “123456.lnk” and “C1.lnk” (the way its suppose to work)

“x1 – Shortcut.lnk” and “c1 – Shortuct.lnk” gives a blank lnk file and and “x1.lnk”

Here is the script I’m using

@echo off
setlocal enabledelayedexpansion

for %%i in ("*.lnk") do (

    set CurrentFile=%%i
    set NewName=!CurrentFile:~0,-15!.lnk
    ren "%%i" "!NewName!"

)
pause
user3491432
  • 91
  • 2
  • 7
  • Instead of `for %%i in ("*.lnk") do (` use `for /F "delims= eol=|" %%i in ('dir /B /A:-D "*.lnk"') do (` (see this for details: [At which point does `for` or `for /R` enumerate the directory (tree)?](https://stackoverflow.com/q/31975093))... – aschipfl Jun 26 '17 at 08:00
  • Firsthand you should get only files with ` - shortcut` in the name and not use a wildcard which gets all .lnk files. THen your substring could work. –  Jun 26 '17 at 09:06

2 Answers2

3

What is happening is that when the file is renamed, the new name is placed later in the directory than the old name, so the for finds the filename again as it processes the names mechanically as it encounters them.

Three solutions

You could change your mask to

for %%i in ("* - shortcut.lnk") do (

You could change your processing to ensure that the shortcut text is still there before renaming by gating the rename

if /i "!CurrentFile:~0,-15!"=="- shortcut.lnk" (
(
 set NewName=!CurrentFile:~0,-15!.lnk
 ren "%%i" "!NewName!"
)

Or you use for /f which builds a list in memory, then processes the list (hence only the "old" names are present)

for /f "delims=" %%i in ('dir /b/a-d "*.lnk" ') do (

or preferably

for /f "delims=" %%i in ('dir /b/a-d "* - shortcut.lnk" ') do (

The second is preferable since the dir command will only select names ending appropriately, so the process can be run repeatedly despite having rnamed files on a prior run.

Magoo
  • 77,302
  • 8
  • 62
  • 84
2

Since you're trying to delete a specific string (rather than generally shorten the filename), you're probably safer using the substitution operator to explicitly remove - Shortcut if present:

@echo off
setlocal enabledelayedexpansion

for %%i in ("*.lnk") do (

    set "CurrentFile=%%i"
    set "NewName=!CurrentFile: - Shortcut=!"
    ren "%%i" "!NewName!"

)
pause
TripeHound
  • 2,721
  • 23
  • 37