Beta 42

Research and Development

Menu

PowerShell - Finding Current Script Path

Here's a useful function that you can paste into your scripts. It will tell you the current location the script is executed from.

function Get-ScriptDirectory{
    $Invocation = (Get-Variable MyInvocation -Scope 1).Value
    try {
        Split-Path $Invocation.MyCommand.Path -ea 0
    }
    catch {
    Write-Warning 'You need to call this function from within a saved script.'
    }
}

Get-ScriptDirectory

Note that the function Get-ScriptDirectory only works from within a saved script. You cannot call it interactively, and you need to save the script in PowerShell ISE before you run it.

The function uses Get-Variable and accesses the built-in variable $MyInvocation from the parent scope (which is your script). If it was accessing $MyInvocation directly from within the function, it would return the caller of the function and not the script location.