Search code examples
batch-fileexeshortcut

shortcut to .exe created by .bat file doesn't work


this is the content of the batch file:

@echo off

set SCRIPT="script.vbs"

echo Set oWS = WScript.CreateObject("WScript.Shell") >> %SCRIPT%
echo sLinkFile = "%~dp0Block Dodger.lnk" >> %SCRIPT%
echo Set oLink = oWS.CreateShortcut(sLinkFile) >> %SCRIPT%
echo oLink.TargetPath = "%~dp0Block Dodger files\Block_Dodger.exe" >> %SCRIPT%
echo oLink.Save >> %SCRIPT%

cscript /nologo %SCRIPT%
del %SCRIPT%

when i run this it does create a correct shortcut to the game.exe but when i start the shortcut i get the following error:

shortcut error

the actual game.exe itself works perfectly fine, even when i manually create a shortcut it works, i dont know why the shortcut created by the batch file doesn't work. how do i fix this?

edit: i dont know if it would matter but the folder Block Dodger files contains other files too that the .exe needs to run, i dont know if these should all be included in the batch file.


Solution

  • I'd have probably done it like this, ensuring that the target path is doublequoted, to protect the space characters:

    @(  Echo Set oWS = WScript.CreateObject("WScript.Shell"^)
        Echo Set oFS = CreateObject("Scripting.FileSystemObject"^)
        Echo sLinkFile = "%~dp0Block Dodger.lnk"
        Echo Set oLink = oWS.CreateShortcut(sLinkFile^)
        Echo oLink.TargetPath = """%~dp0Block Dodger files\Block_Dodger.exe"""
        Echo oLink.WorkingDirectory = "%~dp0Block Dodger files"
        Echo oLink.Save
        Echo oFS.DeleteFile WScript.ScriptFullName) >"script.vbs"
    @%SystemRoot%\System32\cscript.exe /NoLogo "script.vbs"
    

    Other than doublequoting the target path, the only real change is that I'm asking the VBScript to self destruct, instead of deleting it afterwards with @Del "script.vbs". (You can reinstate that as a new last line, and delete Echo Set oFS = CreateObject("Scripting.FileSystemObject"^), and Echo oFS.DeleteFile WScript.ScriptFullName, if you prefer.) Based upon your comment, I've now included an additional property, because the shortcut did not have the Start in: location propagated.