rwallace
rwallace

Reputation: 33385

How to run Microsoft command line compilers from PowerShell

Windows 7, PowerShell 2, Visual Studio 2015, I'm trying to run the command line C# compiler from PowerShell (not the embedded PowerShell within Visual Studio, but a regular, full-blown command window).

In the normal course of events, before using the command line compilers you need to run C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\vcvarsall.bat but that doesn't work here because the environment variables will be set within cmd.exe and then discarded when control returns to PowerShell.

https://github.com/nightroman/PowerShelf supplies Invoke-Environment.ps1 that sounds like it might be the solution, but Invoke-Environment "C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\vcvarsall.bat" does nothing, no effect whatsoever.

Am I using Invoke-Environment the wrong way, or is there something else I should be doing?

Upvotes: 2

Views: 1923

Answers (1)

Luan Vitor
Luan Vitor

Reputation: 83

i've made a simple cmdlet to set the current PowerShell instance to a "developer environment" that i just leave on my $profile, it uses 2 modules from ms, one is to find where visual studio is installed, and the other comes with vs 2019 and up, it is used to power the "vs PowerShell" thing on start menu. here's it:

function Enter-VsDevEnv {
    [CmdletBinding()]
    param(
        [Parameter()]
        [switch]$Prerelease,
        [Parameter()]
        [string]$architecture = "x64"
    )

    $ErrorActionPreference = 'Stop'

    if ($null -eq (Get-InstalledModule -name 'VSSetup' -ErrorAction SilentlyContinue)) {
        Install-Module -Name 'VSSetup' -Scope CurrentUser -SkipPublisherCheck -Force
    }
    Import-Module -Name 'VSSetup'

    Write-Verbose 'Searching for VC++ instances'
    $vsinfo = `
        Get-VSSetupInstance  -All -Prerelease:$Prerelease `
    | Select-VSSetupInstance `
        -Latest -Product * `
        -Require 'Microsoft.VisualStudio.Component.VC.Tools.x86.x64'

    $vspath = $vsinfo.InstallationPath

    switch ($env:PROCESSOR_ARCHITECTURE) {
        "amd64" { $hostarch = "x64" }
        "x86" { $hostarch = "x86" }
        "arm64" { $hostarch = "arm64" }
        default { throw "Unknown architecture: $switch" }
    }

    $devShellModule = "$vspath\Common7\Tools\Microsoft.VisualStudio.DevShell.dll"

    Import-Module -Global -Name $devShellModule

    Write-Verbose 'Setting up environment variables'
    Enter-VsDevShell -VsInstanceId $vsinfo.InstanceId  -SkipAutomaticLocation `
        -devCmdArguments "-arch=$architecture -host_arch=$hostarch"

    Set-Item -Force -path "Env:\Platform" -Value $architecture

    remove-Module Microsoft.VisualStudio.DevShell, VSSetup
}

i leave my profile on gh so, there this function wil always be up-to-date

Upvotes: 1

Related Questions