Search code examples
vbscript

WScript created shortcuts not showing file extensions in filenames


I'm using WScript to generate shortcuts but unlike manually created shortcuts, the filenames don't include the file extensions of the original files. For example, if I create a shortcut in File Explorer with my mouse, let's say "File1.xlsm", the shortcut includes the ".xlsm" part.

Here's an extract of the relevant code.

Set objShellWScript = CreateObject("WScript.Shell")

If objFolder.Files.Count > 0 Then
    
    For Each objFile In objFolder.Files
        
        With objFile
            
            varFilePath = Replace(.Path, varDestinationFolderPath, varShortcutFolderPath, 1, 1)
            
            Set objShortcut = objShellWScript.CreateShortcut(Replace(varFilePath, "." & objFileSystemObject.GetExtensionName(varFilePath), ".lnk"))
            
            With objShortcut
                
                .Description = objFile.Path
                
                .TargetPath = objFile.Path
                
                .Save
                
            End With
            
            Set objShortcut = Nothing 
           
        End With    
    
    Next objFile  
  
End If

Set objShellWScript = Nothing

For what it's worth, I'm using FileSystemObject to loop through the files.

Is there a shortcut property that would help? I've looked around, but the information I've found wasn't particularly helpful. Description shows the file extension to the tootip when you hover over files in File Explorer, close but no cigar.

I've also tried using FileSystemObject MoveFile to see if renaming the files does anything, but no luck.


Solution

  • The argument you pass to CreateShortcut will be used as file name for the shortcut file. The filename, without path and without .lnk is shown in the explorer (or on the desktop).

    The file name itself doesn't need to match the file name it is pointing to. You can create a shortcut with the name "My Homework" that points to "Book1.xlsx".

    If you want to see the file name including extension as shortcut name, you have to pass the filename including extension to CreateShortcut. Just add .lnk at the end of the file (else CreateShortcut will throw a runtime error).

    In your code, you are replacing the extension with .lnk. Instead, just add .lnk at the end of the name (so remove the rename) to keep the extension as part of the name:

    Set objShortcut = objShellWScript.CreateShortcut(varFilePath & ".lnk")
    

    Now the full file name of the shortcut is Book1.xlsx.lnk. Note that Book1.xlsx is the file name (without extension), dots are valid characters in a file name. You even can rename that to My Homework.docx - it is still pointing to the Excel file, the file Icon doesn't change and Windows will open Excel, not Word, when clicking on it.