Blog‎ > ‎IT‎ > ‎

PowerShell Find the Current Path

posted Oct 4, 2015, 5:39 PM by Jake Vosloo   [ updated May 31, 2017, 9:34 PM ]

Powershell has a few complications when finding the path where the current script is executing. Especially if you are running it from ISE or directly on the shell.  This function helps to get the most reliable path.

function Get-ScriptDirectory()
{
    #Try 1, should work for powershell 3.0+.
    try{
        $localPath = $PSScriptRoot
        if (![string]::IsNullOrWhiteSpace($localPath)) {return $localPath}
    } Catch [system.exception] {}
    
    #Try 2, for older version of powershell.
    try{
        if ($myInvocation.MyCommand.CommandType -ne [System.Management.Automation.CommandTypes]::Script) {
            $localPath = [System.IO.Path]::GetDirectoryName($myInvocation.MyCommand.Path)
            if (![string]::IsNullOrWhiteSpace($localPath)) {return $localPath}
        }
    } Catch [system.exception] {}
    
    #Try 3, if this is being run in ISE.
    try{
        $localPath = [System.IO.Path]::GetDirectoryName($psISE.CurrentFile.FullPath)
        if (![string]::IsNullOrWhiteSpace($localPath)) {return $localPath}
    } Catch [system.exception] {}

    #Try 4, as last resort use the current shell location.
    try{
        $localPath = (Get-Location).Path
        if (![string]::IsNullOrWhiteSpace($localPath)) {return $localPath}
    } Catch [system.exception] {}

    #All failed, throw an exception.
    throw "ERROR=""Execution path unknown."" messag=""Unable to identify the path of the script which is needed to load the dependency files."""
}

#Use it like this
[string] $scriptPath = Get-ScriptDirectory
[string] $sourcepath = [System.IO.Path]::GetFullPath((Join-Path ($scriptPath) '.\Source'))

References:


Comments