如何在PowerShell中运行Microsoft命令行编译器
如何在PowerShell中运行Microsoft命令行编译器
我正在尝试从PowerShell运行命令行C#编译器(不是Visual Studio中的嵌入式PowerShell,而是常规的、完整的命令窗口)。
在正常情况下,在使用命令行编译器之前,您需要运行C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\vcvarsall.bat
,但在这里不起作用,因为环境变量将在cmd.exe中设置,然后在控制返回到PowerShell时被丢弃。
https://github.com/nightroman/PowerShelf 提供了Invoke-Environment.ps1,听起来可能是解决方案,但Invoke-Environment "C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\vcvarsall.bat"
没有任何作用,完全没有效果。
我是不是在错误地使用Invoke-Environment,还是有其他事情我应该做?
问题的出现原因:
从内容中可以看出,作者创建了一个PowerShell命令(cmdlet),用于将当前的PowerShell实例设置为一个“开发环境”。这个命令依赖于Microsoft的两个模块,一个用于找到Visual Studio的安装位置,另一个是自带Visual Studio 2019及以上版本的,用于启动开始菜单中的“vs PowerShell”。
解决方法:
作者提供了一个名为"Enter-VsDevEnv"的函数来实现这个命令。函数首先检查是否已安装名为"VSSetup"的模块,如果没有,则使用"Install-Module"命令自动安装。然后,通过"Import-Module"命令引入"VSSetup"模块。接下来,函数搜索VC++实例,获取安装路径,根据处理器架构设置环境变量,并导入名为"Microsoft.VisualStudio.DevShell.dll"的模块。最后,使用"Enter-VsDevShell"命令设置开发环境,并通过"Set-Item"命令设置"Platform"环境变量。
解决方法的代码如下:
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 }
还有一个链接,可以在GitHub上获取完整的profile.ps1文件,以保证这个函数始终是最新的。