pencilCake
pencilCake

Reputation: 53223

How can I set the working directory of a PS Script as the directory where the script exists?

How can set the working directory of a Powershell script as the same directory of the script exists so that regardless of the directory you call it from, it will always look up for the files in the root directory of the script?

For example if you call foo.ps1 as below:

c:> d:\MyScript\foo.ps1

foo.ps1 will set the working directory as d:\MyScript\ so that when it -for example- look up for a configuration file, it will not wsearch it in C:\ but in d:\MyScript\

Upvotes: 5

Views: 7063

Answers (1)

Steve Kaye
Steve Kaye

Reputation: 6262

The path to the script's folder is retrieved using the following code:

Split-Path $MyInvocation.MyCommand.Path

You could use Set-Location (Split-Path $MyInvocation.MyCommand.Path) at the start of the script or you can use Push-Location (Split-Path $MyInvocation.MyCommand.Path) at the start of the script and Pop-Location at the end.

Upvotes: 6

Related Questions