Making PowerShell assume the working directory of a called Batch file

batchbatch filepowershell

I regularly work interactively with a batch script that I can't easily change. One of the features of this script is as a navigation aid – it understands my company/product's code layout conventions and uses that knowledge to turn "theScript cdTestCode" into "cd /D C:\The\Inferred\Path\To\The\Unit\Tests" for the component whose directory I'm currently in. It's a great little timesaver.

I'd like to be able to use this script from within an interactive PowerShell environment. For most of it's many features, just calling the script from within PowerShell works just fine. But for that navigation feature, the directory change it performs only affects the cmd environment PowerShell runs the batch script in. The directory of the surrounding PowerShell host isn't changed, which means it isn't very useful to me when I'm trying to use PowerShell as my shell.

So my question is: Assuming that I cannot change the batch script (and that I don't want to rewrite it as a PowerShell script), is there any good way of propogating the final working directory of the batch script back to the PowerShell host at the completion of the batch script? That is, is there a reasonably simple means writing a function:

function InvokeBatchScriptAndAssumeDirectory($BatchScriptFullName) {
    # ...
}

such that

PS> pwd
Path
----
C:\elsewhere

PS> echo .\mybatchscript.cmd
@ECHO OFF
cd /D C:\

PS> InvokeBatchScriptAndAssumeDirectory .\mybatchscript.cmd
PS> pwd
Path
----
C:\

This question is very similar, but the "solution" it presents is just to change the batch file into a .ps1 script. The batch script I'm working with is very complex – doing that would require a significant rewrite, which I'd prefer to avoid.

Best Answer

I ended up going with @dangph's suggestion.

Param([string]$Script, [string]$ScriptParams)

$WorkingDirectoryTempFile = [IO.Path]::GetTempFileName()
cmd /c " `"$Script`" $ScriptParams && cd > `"$WorkingDirectoryTempFile`" "
Get-Content $WorkingDirectoryTempFile | Set-Location
Remove-Item $WorkingDirectoryTempFile

As an aside, Lee Holmes wrote a script that solves basically the same problem in 2006: http://www.leeholmes.com/blog/2006/05/11/nothing-solves-everything-%e2%80%93-powershell-and-other-technologies/

Related Question