Is it possible to change the directory of a windows console from an app?

こ雲淡風輕ζ 提交于 2021-01-28 10:45:45

问题


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?


回答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.



来源:https://stackoverflow.com/questions/55543814/is-it-possible-to-change-the-directory-of-a-windows-console-from-an-app

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!