powershellshortcut-file

Creating a shortcut with PowerShell


I'm trying to create a shortcut using PowerShell that opens certificates.

$shortcut = (New-Object -ComObject Wscript.Shell).Createshortcut("desktop\Certificates.lnk")
$shortcut.TargetPath = ("C:\Windows\System32\rundll32.exe cryptui.dll,CryptUIStartCertMgr")
$shortcut.IconLocation = ("%SystemRoot%\System32\SHELL32.DLL, 44")
$shortcut.Save()

What I currently have creates a shortcut with the target of...

"C:\Windows\System32\rundll32.exe cryptui.dll,CryptUIStartCertMgr"

When there the shortcut's target includes the "" it doesn't work. I've tried to remove them from the script, but then it launches the certificates gui once and creates a shortcut on the desktop targeted to this PC instead of certificates.


Solution

  • The target executable and its arguments must be specified separately, namely in the .TargetPath and .Arguments property, respectively.[1]

    (Whatever you assign to .TargetPath is considered just an executable file path, and if it contains spaces, it is automatically and invariably enclosed in "..." for you.)

    Therefore:

    $shortcut = (New-Object -ComObject Wscript.Shell).CreateShortcut('desktop\Certificates.lnk')
    $shortcut.TargetPath = 'C:\Windows\System32\rundll32.exe' # Executable only
    $shortcut.Arguments = 'cryptui.dll,CryptUIStartCertMgr'   # Args to pass to executable.
    $shortcut.IconLocation = '%SystemRoot%\System32\SHELL32.DLL, 44'
    $shortcut.Save()
    

    Note that I've removed unnecessary (...) enclosures and, for conceptual clarity, have switched from expandable (double-quoted) strings ("...") to verbatim (single-quoted) strings ('...'), given that no string expansion (interpolation) is required in your code.

    That said, for full robustness you could replace 'C:\Windows\System32\rundll32.exe' with "$env:SystemRoot\System32\rundll32.exe" - for instant expansion - or '%SystemRoot%\System32\rundll32.exe' for letting .CreateShortcut() perform the expansion.[2]


    [1] This contrasts with creating a shortcut file interactively: In the Properties dialog presented by the Windows shell (File Explorer), the single Target field is a concatenation of these two underlying properties; that is, in the GUI you specify only one value - the entire command line - which is then split into executable name/path and arguments behind the scenes.

    [2] It seems that the resulting shortcut file (.lnk) stores both the expanded and the unexpanded value. When inspecting a shortcut file's properties in File Explorer - and surprisingly also via getting the property values of a WshShortcut object created with (New-Object -ComObject Wscript.Shell).CreateShortcut() - you only ever see the expanded values.