workon command doesn't work in Windows PowerShell to activate virtualenv

Raj picture Raj · Aug 14, 2016 · Viewed 9.6k times · Source

I have installed virtualenvwrapper-win and when I try this command

workon <envname>

In CMD it works, but not in Windows PowerShell.

In Windows PowerShell I have to do Scripts\activate.ps1 and then I get the envname before the prompt.

Can you please let me know how can I make workon command working in PowerShell?

Answer

Ansgar Wiechers picture Ansgar Wiechers · Aug 14, 2016

workon is a batch script. If you run it from PowerShell it's launched in a new CMD child process, doing its thing there, then exit and return to the PowerShell prompt. Since child processes can't modify their parent you lose all modifications made by workon.bat when you return to PowerShell.

You basically have two options:

  • Rewrite workon.bat (and the other batch scripts it calls) in PowerShell.

  • Run workon.bat in without exiting from the CMD child process:

    & cmd /k workon <envname>
    

    If you just want a shortcut workon that you can call directly from PowerShell you can wrap that commandline in a function and put the function definition into your PowerShell profile:

    function workon($environment) {
      & cmd /k workon.bat $environment
    }
    

    Use the scriptname with extension here to avoid infinite recursion.