是否可以从应用程序更改Windows控制台的目录? [英] Is it possible to change the directory of a windows console from an app?
问题描述
我的目标是编写一个应用程序,使您可以快速将别名分配给长目录路径并对其进行更改.我写了一个应用程序来管理它们,该应用程序位于用户的appdata目录中的文件中,但是我找不到从我的应用程序中运行该程序的外壳程序目录的更改方法.我的目标是让它从git bash,cmd.exe和powershell运行.我想要这样的东西:
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
现在我对该目录有一个别名"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
我正在使用dotnet core,尽管仔细研究问题似乎根本没有办法做到.使用 Directory.SetCurrentDirectory(path);
或 Environment.CurrentDirectory = path;
,它将更改g.exe进程的工作目录,但是当退出时,shell返回到当我运行命令时,它是工作目录.
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.
我想出了一个git bash解决方案,我更改了我的 g
应用程序以改为输出路径,并将其作为 go
放在我的路径中:>
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
然后我只需要使用.
或 source
来在当前shell中运行脚本:
Then I just need to use .
or source
to run the script in the current shell:
. go reports
批处理文件 go.bat
不需要.
或 source
即可工作:
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%
我想我必须忍受键入额外的字符,但是使用powershell可以做到这一点吗?
I guess I'll have to live with typing the extra characters, but is there a similar way to do this with powershell?
推荐答案
在PowerShell中定义包装函数(假设 g.exe
输出>目标路径):
Define a wrapper function in PowerShell (assuming that g.exe
outputs the target path):
function g { Set-Location (g.exe $args) }
通常,正如 eryksun 在注释中指出的那样,可执行文件-根据定义在子级中运行进程-无法更改其父进程的工作目录.
因此,唯一的解决方案是输出目标目录的路径,并让父进程更改它.
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.
这篇关于是否可以从应用程序更改Windows控制台的目录?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!