Search code examples
powershellbatch-filevisual-studio-codeterminal

How to make a batch file run in vscode terminal


I'm trying to make a batch file that opens a virtual enviroment inside vscode. So far the code looks like this :

if NOT exist ./env (
    pip3 install virtualenv 
    virtualenv env
)
.\env\Scripts\activate.ps1

The if statement works as expected but the command after that does not. However when I run the program in the default terminal for windows, it works as expected.

Edit: I know this is probably not the best way to write the program but I'm new to batch and it works so I'm happy with it for now.

Edit 2: Let me try to better explain what the problem is. I when I run the program in a normal terminal it works just fine. The problem is that I use the terminal in vscode. If I try to just run a normal command in the terminal it says the command was not found (typing the name of the file). When I use the code runner extension it runs the first lines correctly but does not activate the virtual environment


Solution

  • You are mixing batch files and powershell. Those are two separate things. Batch files suffix can be either .bat or .cmd. The powershell files end usually with .ps1.

    Batch files are using the C:\WINDOWS\system32\cmd.exe. Powershell is using the C:\WINDOWS\System32\WindowsPowerShell\v1.0\powershell.exe. As you can see those are two different interpreters.

    If you need to run a .ps1 file that is a powershell script you need to run it in powershell not a .bat file!

    To execute your script you need to execute it like this:

    & 'C:\env\Scripts\activate.ps1'

    If you run it at powershell your if condition will not work anymore. You need to do something like this:

    $PipArgs = @('install', 'virtualenv') 
    if(Test-Path -PathType leaf "C:\env"){
        & 'pip3' $PipArgs
        & 'virtualenv' 'env'
    }