Search code examples
powershellmacosfilealiasshortcut

Create file shortcut/alias on MacOS with PowerShell Core


How do I got about making a file shortcut/alias on MacOS using PowerShell Core?

I have been looking around but have not been able to find any information with creating a shortcut with PowerShell on MacOS. Everything that I have found has been for Windows.

I have a file at ~/Library/COMPANY/apache-jmeter/bin/ApacheJMeter.jar that I would like to create shortcut/alias to on the Desktop ~/Desktop/ApacheJMeter.jar.

I have tried using the method that's used for Windows below:

$WScriptShell = New-Object -ComObject WScript.Shell
        $ShortcutTargetPath = "$InstallPath\apache-jmeter\bin"
        $TargetFile = "$InstallPath\apache-jmeter\bin\jmeter.bat"
        $ShortcutFile = "$env:Public\Desktop\JMeter.lnk"
        $Shortcut = $WScriptShell.CreateShortcut($ShortcutFile)
        $Shortcut.TargetPath = $TargetFile
        $Shortcut.WorkingDirectory = $ShortcutTargetPath
        $Shortcut.Save()

THis results in the following error: New-Object: A parameter cannot be found that matches parameter name 'ComObject'.

I wish I could provide more information but I have not been able to find anything useful.


Solution

  • Shortcut files (.lnk) are only supported by the Windows (GUI) shell, and, similarly, COM is Windows-specific[1], which is why New-Item supports the -ComObject parameter on Windows only.

    On macOS,[2] you have the following options:

    • In the simplest case, create ~/Desktop/ApacheJMeter.jar as a symlink (symbolic link) that references the target file:

      New-Item -Type SymbolicLink $HOME/Desktop/ApacheJMeter.jar -Target $HOME/Library/COMPANY/apache-jmeter/bin/ApacheJMeter.jar
      
      • Note: While ~ usually works to refer to the file-system provider's home location, i.e. the current user's home directory, it does not in a path passed to New-Item's -Target (aka -Value) parameter. Therefore, the command above uses the automatic $HOME variable
    • However, note that this neither allows you to set a working directory nor to pass predefined arguments.

      • If you need either or both of these features, create a shell script instead.

      • If you additionally need to assign a custom icon to your shell script (or symbolic link), you can assign one interactively, via the macOS Finder application; programmatic assignment is possible via the fileicon CLI (authored by me), for instance.


    [1] Strictly speaking, the technology isn't platform-specific, and apparently the macOS Core Foundation C API implements a subset of the functionality - see https://en.wikipedia.org/wiki/Component_Object_Model.

    [2] With the exception of the custom-icon functionality discussed later, the above applies to Linux distros too.