Super User is a question and answer site for computer enthusiasts and power users. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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

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

PS> InvokeBatchScriptAndAssumeDirectory .\mybatchscript.cmd
PS> pwd

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.

share|improve this question
You could write a batch file "launcher" that does two things: (1) Launches the real batch file, and (2) saves the pwd somewhere where it can be retrieved in PowerShell (in the registry I guess). – dangph Dec 10 '13 at 4:13
That is to say, the launcher itself would also be a batch file. – dangph Dec 10 '13 at 4:35
If the final value returned is a path, try $A = C:\mybatchscript.cmd then use that $a variable in your CD command. cd /D $A – Knuckle-Dragger Dec 14 '13 at 9:01

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:

share|improve this answer

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .