Windows Scripting: Creating Windows Shortcuts from the Command Line

Oct 28, 2004 15:02

I've just whipped up a batch script that creates a Windows shortcut (LNK file) with the help of WSH (Windows Script Host).

I was initially going to just use a VBS (Visual Basic Script) file to do this, but I realized that some environment variables aren't available using WSH, whereas they are available in a batch script.

I haven't made the script such that positional parameters can be passed in, but with some slight modification, it could be done.

Anyhoo, here's the script (shortcut.cmd, or shortcut.bat):

@ECHO OFF

SET VBS=%SystemDrive%\Path\To\Temp\VBS\File.vbs
SET LINK=%SystemDrive%\Path\Where\Link\Shall\Be\Placed.lnk
SET TARGET=%SystemDrive%\Path\To\Program\To\Be\Run.exe

ECHO > "%VBS%" Set oWS = WScript.CreateObject("WScript.Shell")
ECHO >>"%VBS%" sLinkFile = "%LINK%"
ECHO >>"%VBS%" Set oLink = oWS.CreateShortcut(sLinkFile)
ECHO >>"%VBS%" oLink.TargetPath = "%TARGET%"
ECHO >>"%VBS%" oLink.Save

"%VBS%"

DEL "%VBS%"
Notice I'm using the %SystemDrive% environment variable. (This will usually get replaced with C:.)

Firstly, it's easier to access environment variables from within a batch script. Here's how I would've had to do that with pure VBS (shortcut.vbs):

Set oWS = WScript.CreateObject("WScript.Shell")
sLinkFile = oWS.Environment.Item("SystemDrive") & "\Path\Where\Link\Shall\Be\Placed.lnk"
Set oLink = oWS.CreateShortcut(sLinkFile)
oLink.TargetPath = oWS.Environment.Item("SystemDrive") & "\Path\To\Program\To\Be\Run.exe"
oLink.Save
Secondly, not all environment variables are accessible from WSH, as I mentioned earlier. Here's a simple test. First, a batch script (test.cmd, or test.bat):

@ECHO OFF

ECHO The environment variable "AllUsersProfile" is equal to %AllUsersProfile%.
The output I get from the batch script is The environment variable "AllUsersProfile" is equal to C:\Documents and Settings\All Users.

However, the equivalent in WSH (test.vbs):

Set oWS = WScript.CreateObject("WScript.Shell")

WScript.Echo "The environment variable ""AllUsersProfile"" is " & oWS.Environment.Item("AllUsersProfile") & "."
The output I get from WSH is The environment variable "AllUsersProfile" is equal to .

In order to get this particular environment variable's value in VBS, you'll actually have to combine the two methods and run the batch file, as I've done with my shortcut.cmd file.

Please also make note that the system in question must have WSH installed and enabled in order for this solution to work properly.

wsh scripting, scripting, geeky, programming, windows

Previous post Next post
Up
[]