Search code examples
powershellbatch-filevisual-studio-2012cmd

Setting up Visual Studio environment variables from PowerShell


I have Visual Studio 9.0 installed but I want to use it manually from PowerShell. It comes with two setup scripts: vcvars32.bat for the 32-bit compiler and vcvars64.bat for the 64-bit compiler. When I open cmd.exe and run one of the scripts, it sets up everything just fine and I can run cl.exe without any problems. When I run one of those setup scripts from PowerShell, though, it doesn't work. The scripts run through fine but trying to run cl.exe afterwards yields a "cl.exe could not be found" error! And looking at the contents of the PATH environment variable after running one of the setup scripts I can see that PATH hasn't actually been modified at all.

So it seems as if the batch files ran from PowerShell maintain their own environment variables state which goes away as soon as the batch file terminates. So is there a way to run batch files from PowerShell and have those batch files affect the actual environment variables of the current PowerShell session? Because that is what I need. All that is done by vcvars32.bit and vcvars64.bit is setting up environment variables after all but it only seems to work from cmd.exe, not from PowerShell.


Solution

  • You should use InvokeEnvironment script to do that. Check its man page:

    Invoke-Environment <path_to_>vsvars32.bat
    

    You can furhter generalize this by determining OS bits and crafting the vsvars<OsBits>.bat.

    Example:

    PS C:\Program Files (x86)\Microsoft Visual Studio 14.0\Common7\Tools> $env:INCLUDE -eq $null
    PS C:\Program Files (x86)\Microsoft Visual Studio 14.0\Common7\Tools> $true
    PS C:\Program Files (x86)\Microsoft Visual Studio 14.0\Common7\Tools> Invoke-Environment .\vsvars32.bat
    PS C:\Program Files (x86)\Microsoft Visual Studio 14.0\Common7\Tools> $env:INCLUDE
    C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\INCLUDE;C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\ATLMFC\INCLUDE;C:\Program Files (x86)\Windows Kits\10\include\10.0.10586.0\ucrt;C:\Program Files (x86)\Windows Kits\NETFXSDK\4.6.1\include\um;C:\Program Files (x86)\Windows Kits\10\include\10.0.10586.0\shared;C:\Program Files (x86)\Windows Kits\10\include\10.0.10586.0\um;C:\Program Files (x86)\Windows Kits\10\include\10.0.10586.0\winrt;