Search code examples
powershellworking-directorypsake

psake set execution directory


I’m trying to move form MSBuild to psake.

My repository structure looks like this:

.build
 | buildscript.ps1
.tools
packages
MyProject
MyProject.Testing
MyProject.sln

I want to clean the repository before building (using git clean -xdf). But I can’t find a way (expect with the .Net classes) to set the execution directory of git.

First I searched for a way to set the working directory in psakes exec:

exec { git clean -xdf }
exec { Set-Location $root
       git clean -xdf }

Set-Location works but after the exec block is finished the location is still set to $root.

Then I tried:

Start-Process git -Argumentlist "clean -xdf" -WorkingDirectory $root

Which works but keeps git open and no future task gets executed.

How can I execute git in $root?


Solution

  • I've encountered the same exact problem as yours in psake with my build scripts. The "Set-Location" cmdlet doesn't affect the Win32 working directory for your Powershell session.

    Here is an example:

    # Start a new PS session at "C:\Windows\system32"
    Set-Location C:\temp
    "PS Location = $(Get-Location)"
    "CurrentDirectory = $([Environment]::CurrentDirectory)"
    

    The output will be:

    PS Location = C:\temp
    CurrentDirectory = C:\Windows\system32
    

    What you probably need to do is change the Win32 current directory before invoking native commands such as "git":

    $root = "C:\Temp"
    exec {
      # remember previous directory so we can restore it at end
      $prev = [Environment]::CurrentDirectory
      [Environment]::CurrentDirectory = $root
    
      git clean -xdf
    
      # you might need try/finally in case of exceptions...
      [Environment]::CurrentDirectory = $prev
    }