How to change the cmd's current-dir using PowerShell?

感情迁移 提交于 2019-12-20 05:43:12

问题


I read some file using PowerShell, and change current dir accordingly, but all I can do is change the current PowerShell's current dir, not the caller's dir (the cmd.exe environment that called that ps1 file). Things I tried:

powershell ch-dir.ps1 | cd

(won't work, obviously, since CD is internal command)

powershell cd $myDir

(changes current dir in PowerShell, but when script exits, the cmd environment still in original dir)

I really hope I won't need to find the script's caller process (the cmd), and make a change in it's cur-dir by-force... (or even worse - to save the dir I want in some env-var and then cd %my_var% since it would require two lines of command)


回答1:


I'm not sure if this meets your needs, but if you set it up so that the only output from your powershell script is your desired new working directory, you could do this:

c:\>for /F %i IN ('powershell -noprofile -command "write-output 'c:\users'" ') DO @cd %i
c:\Users>



回答2:


The cmd prompt is hosting your powershell session, unless you can figure out a way to return an exit code to the prompt that will (on exit code 99999) change directory to (predefined values, switch?). As far as powershell is concerned they're different processes.

Heres a good example for you to try: Open a cmd prompt. Open task manager, find cmd.exe In your cmd prompt type Powershell View powershell as a different process (check the PID.) End the powershell process. Watch what happens.

Alternatively, if you need something run from cmd in a specific directory based on logic in your powershell script, you can invoke it with a cmd /c from within Powershell.



来源:https://stackoverflow.com/questions/16045457/how-to-change-the-cmds-current-dir-using-powershell

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