1

I have to extract source filename from .lnk shortcut in batch. The extracted text must be in (program name).(extension) form.

I must admit that I'm a complete laic, when it comes to batch (or any scripting actually), so any help concerning my question is highly appreciated.

5
  • Why do you need to do it in shell script (batch)? It's much simpler in PowerShell. Commented Dec 15, 2014 at 20:58
  • I'm doing a one-time assignment, which I'm unfortunately too deep into to switch to PowerShell (in which I have absolutely no experience). Commented Dec 15, 2014 at 21:04
  • You would need to extract the metadata from the .lnk file to do this. This is not trivial in batch, but very easy in a VBScript/JScript script or PowerShell. Commented Dec 15, 2014 at 21:05
  • If the batch file can open the VBScript, then this is not a problem. The outcome has to come back to batch though. My script would be quite tangled, but as for now, only the outcome matters. Unfortunately, I have no idea how to do so. Commented Dec 15, 2014 at 21:13
  • As you can see from the reply from rojo, a "pure" shell script solution is pretty painful (requires slow WMIC). A VBS solution would probably be faster and easier. Commented Dec 15, 2014 at 21:36

1 Answer 1

5

You can do it with a wmic query to win32_shortcutfile. Just make sure all your backslashes are backslash-escaped within %filename%.

@echo off
setlocal

:: ensure user supplied a filename with a .lnk extension
if /i "%~x1" neq ".lnk" (
    echo usage: %~nx0 shortcut.lnk
    goto :EOF
)

:: set filename to the fully qualified path + filename
set "filename=%~f1"

:: convert single backslashes to double
set "filename=%filename:\=\\%"

:: get target
for /f "tokens=1* delims==" %%I in ('wmic path win32_shortcutfile where "name='%filename%'" get target /format:list ^| find "="') do (
    echo(%%J
)

What you want ends up in %%J. If you only want the target filename.ext, change that to %%~nxJ. If you want only the drive and path, change it to %%~dpJ. See the last page of help for in a cmd console for more info about variable expansion.

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

3 Comments

Thank you very much for your help. Now I'll try and implement that into my puzzle.
I know this thread is ancient but how do you run this code when the link is on a server? Instead of C:\myLink.lnk I have \\myServer\myLink.lnk The code gives the error "No Instance(s) Available."
somehow the script not work and print: find: ‘=’: No such file or directory, so I just use Format-Hex <path to lnk> from powershell as alternative to see the executable path.

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.