Microsoft:Scripting:WSH

From My Notepad
Jump to: navigation, search

Using WSH to create a shortcut to a file, if it exists

The following WSH VBScript does the following

  1. Checks to see if the file C:\Program Files\My Program\my program.exe exists.
  2. If it does exist, it creates a shortcut My Program.lnk on the All Users Desktop.

Please note that you must use double back slashes in the ExecQuery line for the file specification. This is due to the use of slashes in a SQL like query.

strComputer = "."

Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\cimv2")

Set colFiles = objWMIService. _
    ExecQuery("Select * From CIM_DataFile Where Name = 'C:\\Program Files\\My Program\\my program.exe'")

If colFiles.Count = 0 Then
    Wscript.Quit
End If

Dim    WSHShell
Set    WSHShell = WScript.CreateObject("WScript.Shell")
strLocalFolder = WSHShell.SpecialFolders("AllUsersDesktop")

Set shortCut = WSHSHell.CreateShortcut(strLocalFolder & "\My Program.lnk")

shortCut.TargetPath = "C:\Program Files\My Program\my program.exe"
shortCut.IconLocation = "C:\Program Files\My Program\my program.exe,0"
shortCut.Save