Skip to content

Get current script path

Getting the current script path programmatically when running a script is a nice little feature to have when a sub command in your script demands an absolute path and the script is not always run from same path from time to time.

Often when building larger set of scripts which calls a lot of external components that are not Powershell you sometimes get old janky .exe files that demands an absolute path to even work when called from within a script even if they are in the same folder as the script itself.

The code takes the full path of the script including the script name and then splits the value and removing the script name from the path so you end up only with the path where it was run from and adds it to a variable.

1
2
3
4
5
6
7
8
9
function Get-ScriptDirectory
{
$Invocation = (Get-Variable MyInvocation -Scope 1).Value
Split-Path $Invocation.MyCommand.Path
}

$path = Get-ScriptDirectory

Write-Output $path"\ThisCanBeAddedOn"