Search code examples
powershellpsake

Getting the current directory where the script is executed as opposed to the current executing directory of the script


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! :)


Solution

  • 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