PowerShell: Set the Location the Executing Script Path

I already knew about the proper way to get the executing path:

Split-Path -Path $MyInvocation.MyCommand.Definition -Parent

…but today I’ve saw another way to set the scope of the current location to a desired path (open-source code is the most powerful resource):


Adds the current location to the top of a location stack.

Push-Location [[-Path] <String>] [-PassThru] [-StackName <String>] [-UseTransaction [<SwitchParameter>]]

Push-Location [-LiteralPath <String>] [-PassThru] [-StackName <String>] [-UseTransaction [<SwitchParameter>]]

The Push-Location cmdlet adds (“pushes”) the current location onto a location stack. If you specify a path,
Push-Location pushes the current location onto a location stack and then changes the current location to the
location specified by the path. You can use the Pop-Location cmdlet to get locations from the location stack.

By default, the Push-Location cmdlet pushes the current location onto the current location stack, but you can use
the StackName parameter to specify an alternate location stack. If the stack does not exist, Push-Location creates

For more information about location stacks, see the Notes.

Online Version: http://go.microsoft.com/fwlink/p/?linkid=293892

To see the examples, type: “get-help Push-Location -examples”.
For more information, type: “get-help Push-Location -detailed”.
For technical information, type: “get-help Push-Location -full”.
For online help, type: “get-help Push-Location -online”

It is actually a stack, so it could be very useful in situation where you need to temporary change the scope of the location for a sets of commands and then return back to the previous path. This is mandatory when your script is a part of a bigger script, and you also don’t have the ownership (think about PsGet) of that script, so it’s a best practice to push your needed location, and before the script ends pop it (Pop-Location) to resume the path used from the script who called your.

Combining together both commands you just have to add on the top of the script this command:

Push-Location (Split-Path -Path $MyInvocation.MyCommand.Definition -Parent)

The follow is the sample script where I’ve saw this command in action, it is a PsGet script to enable posh-git module (profile.example.ps1):

Push-Location (Split-Path -Path $MyInvocation.MyCommand.Definition -Parent)

# Load posh-git module from current directory
Import-Module .\posh-git

# If module is installed in a default location ($env:PSModulePath),
# use this instead (see about_Modules for more information):
# Import-Module posh-git

# Set up a simple prompt, adding the git prompt parts inside git repos
function global:prompt {

    # Reset color, which can be messed up by Enable-GitColors
    $Host.UI.RawUI.ForegroundColor = $GitPromptSettings.DefaultForegroundColor

    Write-Host($pwd.ProviderPath) -nonewline


    return "> "



Start-SshAgent -Quiet