powershellpathworking-directory

Can I get the current console filepath from which a script was invoked from within said script?


If I am in the console/terminal at the C:\temp location, and I invoke the script C:\scripts\test.ps1, how can I get the path of the current folder (C:\temp) from inside the script I just invoked?

None of the following has the required information:


Solution

  • Note:


    PowerShell's current location vs. its current directory, PowerShell-specific vs. native file-system paths:

    tl;dr

    Read on for background information.


    Get-Location reports PowerShell's current location, which, however, isn't guaranteed to be a file-system location, given that a PowerShell provider other than the FileSystem provider could be the one underlying the current location - even though that is rare in practice.

    Therefore, to robustly determine the full path of the current file-system location, use the following:

    (Get-Location -PSProvider FileSystem).Path
    

    Note that the above expresses the file-system location potentially in terms of PowerShell-only drives, namely if the path passed to Set-Location was expressed in terms of a drive created with New-PSDrive.

    Therefore, to robustly determine the full path of the current file-system location as a native file-system path, use .ProviderPath instead of .Path:

    # .ProviderPath only differs from .Path if the current
    # file-system location is on a PowerShell-only drive
    # (a non-persistent drive established with New-PSDrive)
    (Get-Location -PSProvider FileSystem).ProviderPath
    

    In the simplest case - if you're willing to assume that the current location is a file-system location - you can use the automatic $PWD variable, which is in effect a more efficient alternative to calling Get-Location without arguments.

    # Same as: (Get-Location).Path
    $PWD.Path  # same as: "$PWD" (stringified)
    

    Note: