Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the best way to determine the location of the current PowerShell script?

Whenever I need to reference a common module or script, I like to use paths relative to the current script file. That way, my script can always find other scripts in the library.

So, what is the best, standard way of determining the directory of the current script? Currently, I'm doing:

$MyDir = [System.IO.Path]::GetDirectoryName($myInvocation.MyCommand.Definition) 

I know in modules (.psm1) you can use $PSScriptRoot to get this information, but that doesn't get set in regular scripts (i.e. .ps1 files).

What's the canonical way to get the current PowerShell script file's location?

like image 603
Aaron Jensen Avatar asked Mar 28 '11 23:03

Aaron Jensen


People also ask

How do I find the location of a PowerShell script?

To get the full path of the script we need to use the $myInvocation command. This is an automatic variable and it is only invoked when the script or the function is executed. $MyInvocation.

How do I reference the current directory in PowerShell?

PowerShell Get Current Directory of Script File To get current directory of script file or running script, use $PSScriptRoot automatic variable. PSScriptRoot variable contains full script to path which invoke the current command.


1 Answers

PowerShell 3+

# This is an automatic variable set to the current file's/module's directory $PSScriptRoot 

PowerShell 2

Prior to PowerShell 3, there was not a better way than querying the MyInvocation.MyCommand.Definition property for general scripts. I had the following line at the top of essentially every PowerShell script I had:

$scriptPath = split-path -parent $MyInvocation.MyCommand.Definition 
like image 191
JaredPar Avatar answered Sep 28 '22 05:09

JaredPar