Search code examples
.netwindowsvbscriptregistry

Cannot modify .LNK file using VBScript


I am trying to change arguments of shortcut, .LNK file. I have this code:

Set objFolder = fileSystem.GetFolder(folderPath)
Set colFiles = objFolder.Files

For Each objFile in colFiles
    If ( InStr(objFile.Name, ".lnk") ) Then

        Set oShellLink = WshShell.CreateShortcut(objFile.Name)
        Wscript.Echo oShellLink.TargetPath
        if ( InStr(oShellLink.TargetPath, "test.exe") ) Then
            UpdateShortcut(oShellLink)
        End If
    End If
Next

Function UpdateShortcut(shellLink)
    shellLink.Arguments = "-m Hello"
    shellLink.Save
    Wscript.Echo shellLink.Arguments
End Function

And I am getting really strange behavior. I have 2 shortcuts on Desktop named Test.lnk and Test - Copy.lnk and one in C:\ProgramData\Microsoft\Windows\Start Menu\Programs. In order to modify the third one, I need write permissions, so I have this code at the start of my vbsript:

If Not WScript.Arguments.Named.Exists("elevate") Then
  CreateObject("Shell.Application").ShellExecute WScript.FullName _
    , """" & WScript.ScriptFullName & """ /elevate", "", "runas", 1
  WScript.Quit
End If

Now, by running my vbscript, this command executes Wscript.Echo shellLink.Arguments three times and a three MessageBoxes popup saying "-m Hello", meaning shellLink.Save got executed with no errors. But none of link files get changed. However if I run without administrative rights, the two link files on the desktop get changed, but the third one does not. Also, sometimes, for some unknown reason I can't read shellLink.TargetPath property, which I need in order to figure out is this the right link/shortcut I need to edit.

My question is what am I doing wrong and is there any other (better) way of changing arguments in .LNK (shortcut) file? Also I should mention, I am running Windows 10.


Solution

  • Using

    Set oShellLink = WshShell.CreateShortcut(objFile.Name)
    

    creates/modifies shortcuts in the current working directory, so you're basically creating new shortcuts in a different location rather than modifying the existing ones.

    Change this:

    Set oShellLink = WshShell.CreateShortcut(objFile.Name)

    into this:

    Set oShellLink = WshShell.CreateShortcut(objFile.Path)

    and the problem will disappear.