1

My code now creates a shortcut to first row in "list.txt", with correct name (as last folder in target of shortcut called), but I need to do the same process with whole "list.txt", for each row, as if I added 'skip=1', then 'skip=2'..... to 'for /f' for each row:

for /f "skip=1 usebackq delims=" %%G IN (List.txt) DO if not defined line set "line=%%G"

I can't repeat this process in one bat file to each row. How to do that?

@echo off
Setlocal EnableExtensions
for /f "usebackq delims=" %%G IN (List.txt) DO if not defined line set "line=%%G"
set LNKNAME=%line:~0%
for %%f in ("%LNKNAME%") do set LNKNAME_A=%%~nxf
SET SAVETO=%userprofile%\desktop

    call :createLink "%LNKNAME_A%" "%line%"

pause

rem createLink <linkname> <target>
:createLink
set SCRIPT="%TEMP%\%RANDOM%-%RANDOM%-%RANDOM%-%RANDOM%.vbs"
echo Set oWS = WScript.CreateObject("WScript.Shell") >> %SCRIPT%
echo sLinkFile = "%SAVETO%\%~1.lnk" >> %SCRIPT%
echo Set oLink = oWS.CreateShortcut(sLinkFile) >> %SCRIPT%
echo oLink.TargetPath = "%~2" >> %SCRIPT%
echo oLink.Save >> %SCRIPT%
cscript /nologo %SCRIPT%
del %SCRIPT%
EXIT /B 0
rem goto :eof
Stz
  • 61
  • 10

1 Answers1

1

just expand your loop:

@echo off
Setlocal EnableExtensions enabledelayedexpansion
SET "SAVETO=%userprofile%\desktop"
for /f "usebackq delims=" %%G IN ("List.txt") DO (
  set "line=%%G"
  set "LNKNAME=!line:~0!"
  for %%f in ("!LNKNAME!") do set "LNKNAME_A=%%~nxf"
  call :createLink "!LNKNAME_A!" "!line!"
)
pause
goto :eof
:createLink
...

Note: this uses delayed expansion

Edit moved set saveto=... out of the loop (no benefit to set it to the same value for each line)

Considering set "LNKNAME=!line:~0!" does nothing useful, we can remove it and use %%G directly. Also the for %%f does just get %%~nxf (you haven't provided an example of your text file, so I have to guess: shouldn't it be just %%~nf?), which is the same as %%nxG(%%~nG?), we can also remove it and use %%G and %%nG directly. This shortens the code to:

@echo off
Setlocal EnableExtensions  
SET "SAVETO=%userprofile%\desktop"
for /f "usebackq delims=" %%G IN ("List.txt") DO (
  call :createLink "%%~nG" "%%G"
)
...

(Note: no delayed expansion needed any more)

Stephan
  • 53,940
  • 10
  • 58
  • 91
  • Thank you for your reply, but that still creates only one shortcut for the first row of List.txt, should I also change something in **:createLink** part? – Stz Oct 29 '18 at 12:08
  • Again, thank you very much! I've just changed: `if not defined line set "line=%%G"` to `set "line=%%G"` and now it works great! – Stz Oct 29 '18 at 12:28
  • 1
    few bits shorter: `SET "SAVETO=%userprofile%\desktop"` `for /f "usebackq delims=" %%G IN (List.txt) DO if exist "%%~fG" call :createLink "%%~nxG" "%%~G"` `pause &goto :eof` – penknife Oct 29 '18 at 19:23
  • Yeah, cool! Much shorter and still doing the same, thank you! – Stz Oct 30 '18 at 12:15