powershell

Get proper startup directory in PowerShell when executed via a shortcut file


I have a shortcut file that points to a PowerShell script file that is located in a different directory, and when that PowerShell script is executed via the shortcut file I require to obtain the proper startup directory (the directory where the shortcut file is) to set it in a variable like this:

$gamesDirPath = "{Current Shortcut Directory}\Games"

None from these suggestions seems to return the proper directory.

Note that I'm on PowerShell 5.x

Maybe this question would have an easy solution, but I also tried various times to ask to ChatGPT and each time it does not understand well the question, it demands me to set the location of the .lnk file in a variable inside the script!. Weird. Of course the shortcut file can be located anywhere.


Solution

  • As stackprotector notes, an executable launched from a shortcut file (.lnk) knows nothing about the latter.

    However, you can infer the directory in which the shortcut is located as long as you don't specify an explicit working directory (i.e. as long as you leave Start in: field in the shortcut-file Properties dialog empty).


    As an alternative to creating a shortcut file, consider creating a symbolic link to your script file, which then causes the latter to see the link's full path and directory in the automatic $PSCommandPath and $PSScriptRoot variables.

    Caveat:

    #requires -RunAsAdministator
    
    New-Item -Force -ItemType SymbolicLink C:\path\to\link.ps1 -Target C:\different-path\to\original.ps1
    

    When invoked via symlink C:\path\to\link.ps1, C:\different-path\to\original.ps1 then sees the following values:

    Note:


    [1] You get the following warning: "Turning on developer mode, including installing and running apps from outside the Microsoft Store, could expose your device and personal data to security risks or harm your device."