Get current power-shell script directory path in your power-shell script

powershellAt times while writing power-shell scripts, you may need to refer to directory path of your current script in your script. The most common reasons for doing this may include referring to any content at the same location or relative to the current script’s location.

If the above line is confusing or needs more explanation, here is an example (Though if the matter is clear, you can skip this paragraph). I have a power-shell script, from which I want to refer to a file placed at the same location where my script-file is located; say other-file. I would be providing this whole folder (i.e. the script-file and the other-file inside it) to a client. Now I don’t know where the client would place this folder on his machine. So to correctly refer to the other-file while executing the script-file, I can get the script-file’s location and refer the other-file using this path. This would allow me to correctly refer to the other-file irrespective to its folder location.

This can be achieved through the following command:

$scriptPath = split-path -parent $MyInvocation.MyCommand.Definition

If you are using PowerShell 3.0 or later, you can also use the following command to achieve the same result (in case you are wondering which version of power-shell are you using, refer my other post Power-shell command to determine the version of installed power-shell engine):

$scriptPath = split-path -parent $PSCommandPath

Just to note: the two commands “$MyInvocation.MyCommand.Definition” and “$PSCommandPath” both provide the full path of currently executing script. So in above solution we are getting the parent folder path from this full path.

Happy POWER scripting !!