Powershell & VCVars Batch

Recently, I have been doing more and more work with PowerShell, which is a very good thing. PowerShell is far more powerful than the “classic” batch files, and one of the feature I love is the ability to use the .NET framework right in there.

The downside for development is the fact that Visual Studio environments are not set properly. Typically, I would start the Visual Studio command prompt and then launch PowerShell. This works most of the time as I typically only build one platform.

But, doing a bit of research, I found that I can run the vcvars batch file, and then get a list of all the environment variables. Thanks to Niclas Lindgren and Chris Tavares, I merged and modified their scripts into this small function that allows PowerShell to set up its environment as if vcvars was run. Another big thing is that you can change the environment halfway through, such as if you are building for both x86 and x64.

function VsVarsAll($version = "14.0", $platform = "x86") {
    # handle 64-bit OS differences
    $64bit = !(gv PSHOME).Value.ToLower().Contains("syswow64")
    $HKLM = "HKLM:\SOFTWARE"
    if ($64bit) {
        $HKLM = "HKLM:SOFTWARE\Wow6432Node"
    }

    # get the path to vcvarsall.bat
    $VsRoot = (gp "$HKLM\Microsoft\VisualStudio\$version").ShellFolder
    $file = [System.IO.Path]::Combine($VsRoot, "VC", "vcvarsall.bat")

    # run the .bat, and return a list of all the envvars
    $cmd = "`"$file`" $platform & set"
    cmd /c $cmd | Foreach-Object {
        # parse the variables, and set them in powershell
        $p, $v = $_.split('=')
        Set-Item -path env:$p -value $v
    }

    # cool factor: update the title
    [System.Console]::Title = "VS $version - $platform Windows PowerShell"
}

To set up for x86 development, just run:

VsVarsAll -platform "x86"

Similarly, for x64:

VsVarsAll -platform "x64"

If you are running an older/newer Visual Studio, you can set the version:

VsVarsAll -version = "14.0" -platform "x86"