2

My goal is to write an app that lets you quickly assign aliases to long directory paths and change to them. I wrote an app that manages them in a file in the user's appdata directory, but I can't find a way to change the directory of the shell I run the program in from my app. My goal is to have it work from git bash, cmd.exe, and powershell. I want something like this:

cd /c/vsts/some-long-project-name-reports
g -a reports

Now I have an alias 'reports' for that directory. What I want to do get to that directory next time I open a console is:

g reports

I'm using dotnet core, though looking through questions it seems like there isn't a way to do this at all. With Directory.SetCurrentDirectory(path); or Environment.CurrentDirectory = path; it changes the working directory of the g.exe process, but when it exits the shell goes back to it's working directory when I ran the command.

I've come up with a solution for git bash, I changed my g app to output the path instead and have this as go in my path:

OUTPUT="$(g $1)"
cd $OUTPUT

Then I just need to use . or source to run the script in the current shell:

. go reports

And batch file go.bat doesn't need the . or source to work:

for /F "tokens=*" %%i in ('g %1') do set OUTPUT=%%i
cd %OUTPUT%

I guess I'll have to live with typing the extra characters, but is there a similar way to do this with powershell?

Jason Goemaat
  • 28,692
  • 15
  • 86
  • 113
  • In a command prompt type `doskey /?`. See my answer here https://stackoverflow.com/questions/54956072/can-i-create-shorthand-names-for-use-inside-cmd – Noodles Apr 05 '19 at 21:57
  • 1
    There's no such thing as "the directory of a windows console" (it's an I/O device with input/screen buffer files that are associated with a window), so I suppose what you want is to change the working directory of a parent process, specifically for the command-line shells that you've listed. There's no general solution for that. I could speculate on hacky workarounds, but you've already found the best solution for CMD, using a batch script. For bash and PowerShell, I suggest that you implement this using a function instead of a script. – Eryk Sun Apr 06 '19 at 00:45

1 Answers1

1

Define a wrapper function in PowerShell (assuming that g.exe outputs the target path):

function g { Set-Location (g.exe $args) }

Generally, as eryksun points out in a comment, an executable - which by definition runs in a child process - cannot change its parent process' working directory.
Therefore, the only solution is to output the target directory's path and let the parent process change to it.

mklement0
  • 382,024
  • 64
  • 607
  • 775