2

I want to get the current directory where the script is executed as opposed to the current executing directory of the script.

The script lives in 'd:\projects\code\development.tools' and I want the directory of the project that lives in 'd:\projects\code\development\ace\ace.testing'

Now, here is the thing when I do 'Write-Host $Env:PWD' or just '$Env:PWD' outside to Psake Properties I actually get what I want but when I try to get it from within the Properties it returns what $PWD returns and that is the executing directory of the script.

Write-Host $Env:PWD # returns d:\projects\code\development\ace\ace.testing

Properties {
    $baseDir = $Env:PWD # returns d:\projects\code\development\.tools
}

I'm not sure what's happening here but I can't figure it out.

I tried to store the correct path in a variable but it didn't really work.

UPDATE:

After spending few hours on that I realized it's actually working! I was working on that script on and off and put a throw statement somewhere and forgot that it's there! so I thought Psake is doing something weird and because of that it doesn't work but yeah Psake is pure! ;)

So if you want to get the current directory in which the script is being executed $Env:PWD seems to do it! :)

iam3yal
  • 2,188
  • 4
  • 35
  • 44

2 Answers2

8

To get the location of the script being executed:

Split-Path $myInvocation.MyCommand.Path

To get the path of the present working directory:

(Get-Item -Path '.\' -Verbose).FullName
EBGreen
  • 36,735
  • 12
  • 65
  • 85
0

After spending few hours on that I realized it's actually working! I was working on that script on and off and put a throw statement somewhere and forgot that it's there!

So if you want to get the current directory in which the script is being executed $Env:PWD seems to do it! :)

iam3yal
  • 2,188
  • 4
  • 35
  • 44
  • Don't think this is universal. I'm using the new pwsh 7.0 and $Env:PWD returns null. Pretty new machine too. @EBGreen's answer works best. – Connor Low May 05 '20 at 16:48
  • 1
    @ConnorLow Thanks, I changed the accepted answer even though for my use-case it worked. – iam3yal May 05 '20 at 23:00