簡體   English   中英

如何將 PowerShell 與 Visual Studio 命令提示符一起使用?

[英]How can I use PowerShell with the Visual Studio Command Prompt?

我已經使用 Beta 2 一段時間了,它讓我抓狂,因為在運行 Visual Studio 2010 命令提示符時我必須輸入 cmd.exe。 我曾經有一個很好的vsvars2008.ps1腳本用於 Visual Studio 2008。是否有vsvars2010.ps1腳本或類似的腳本?

從這里大量竊取: http : //allen-mack.blogspot.com/2008/03/replace-visual-studio-command-prompt.html ,我能夠讓它工作。 我將以下內容添加到我的 profile.ps1 中,一切都很好。

pushd 'c:\Program Files (x86)\Microsoft Visual Studio 10.0\VC'
cmd /c "vcvarsall.bat&set" |
foreach {
  if ($_ -match "=") {
    $v = $_.split("="); set-item -force -path "ENV:\$($v[0])"  -value "$($v[1])"
  }
}
popd
write-host "`nVisual Studio 2010 Command Prompt variables set." -ForegroundColor Yellow

多年來,這一直運行良好 - 直到 Visual Studio 2015。vcvarsall.bat 不再存在。 相反,您可以使用位於 Common7\\Tools 文件夾中的 vsvars32.bat 文件。

pushd 'C:\Program Files (x86)\Microsoft Visual Studio 14.0\Common7\Tools'    
cmd /c "vsvars32.bat&set" |
foreach {
  if ($_ -match "=") {
    $v = $_.split("="); set-item -force -path "ENV:\$($v[0])"  -value "$($v[1])"
  }
}
popd
write-host "`nVisual Studio 2015 Command Prompt variables set." -ForegroundColor Yellow

Visual Studio 2017 的情況再次發生了變化。 vsvars32.bat似乎已被放棄,以支持VsDevCmd.bat 確切路徑可能因您使用的 Visual Studio 2017 版本而異。

pushd "C:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\Common7\Tools"
cmd /c "VsDevCmd.bat&set" |
foreach {
  if ($_ -match "=") {
    $v = $_.split("="); set-item -force -path "ENV:\$($v[0])"  -value "$($v[1])"
  }
}
popd
Write-Host "`nVisual Studio 2017 Command Prompt variables set." -ForegroundColor Yellow

最簡單的選擇是運行 VS 2010 命令提示符,然后啟動 PowerShell.exe。 如果您真的想從“主頁”PowerShell 提示符執行此操作,那么您展示的方法就是要走的路。 我使用了 Lee Holmes 不久前寫的一個腳本:

<#
.SYNOPSIS
   Invokes the specified batch file and retains any environment variable changes
   it makes.
.DESCRIPTION
   Invoke the specified batch file (and parameters), but also propagate any  
   environment variable changes back to the PowerShell environment that  
   called it.
.PARAMETER Path
   Path to a .bat or .cmd file.
.PARAMETER Parameters
   Parameters to pass to the batch file.
.EXAMPLE
   C:\PS> Invoke-BatchFile "$env:VS90COMNTOOLS\..\..\vc\vcvarsall.bat"       
   Invokes the vcvarsall.bat file to set up a 32-bit dev environment.  All 
   environment variable changes it makes will be propagated to the current 
   PowerShell session.
.EXAMPLE
   C:\PS> Invoke-BatchFile "$env:VS90COMNTOOLS\..\..\vc\vcvarsall.bat" amd64      
   Invokes the vcvarsall.bat file to set up a 64-bit dev environment.  All 
   environment variable changes it makes will be propagated to the current 
   PowerShell session.
.NOTES
   Author: Lee Holmes    
#>
function Invoke-BatchFile
{
   param([string]$Path, [string]$Parameters)  

   $tempFile = [IO.Path]::GetTempFileName()  

   ## Store the output of cmd.exe.  We also ask cmd.exe to output   
   ## the environment table after the batch file completes  
   cmd.exe /c " `"$Path`" $Parameters && set > `"$tempFile`" " 

   ## Go through the environment variables in the temp file.  
   ## For each of them, set the variable in our local environment.  
   Get-Content $tempFile | Foreach-Object {   
       if ($_ -match "^(.*?)=(.*)$")  
       { 
           Set-Content "env:\$($matches[1])" $matches[2]  
       } 
   }  

   Remove-Item $tempFile
}

注意:此功能將在即將推出的基於PowerShell 社區擴展2.0 模塊的版本中提供。

我在這里找到了一個簡單的方法:修改快捷方式。

原來的快捷方式是這樣的:

%comspec% /k ""C:\Program Files (x86)\Microsoft Visual Studio 12.0\Common7\Tools\VsDevCmd.bat""

在最后一個引用之前添加& powershell ,如下所示:

%comspec% /k ""C:\Program Files (x86)\Microsoft Visual Studio 12.0\Common7\Tools\VsDevCmd.bat" & powershell"

如果想讓它看起來更像 PS,請轉到快捷方式屬性的“顏色”選項卡,將紅色、綠色和藍色值分別設置為 1、36 和 86。

截屏

一個老問題,但值得另一個答案 (a) 提供 VS2013 支持; (b) 結合之前兩個答案中的最佳答案; (c) 提供一個函數包裝器。

這建立在@Andy 的技術上(它建立在安迪指出的艾倫麥克的技術上(這反過來又建立在艾倫指出的羅伯特·安德森的技術上(所有這些都有一個小故障,如用戶在此頁面上所指出的,僅稱為“我- -”,所以我也考慮到了)))。

這是我的最終代碼——注意在正則表達式中使用非貪婪量詞來處理值中任何可能的嵌入等於。 這也恰好簡化了代碼:單個匹配而不是匹配然后像 Andy 的示例中那樣拆分,或者像“me--”的示例中那樣匹配然后 indexof 和子字符串)。

function Set-VsCmd
{
    param(
        [parameter(Mandatory, HelpMessage="Enter VS version as 2010, 2012, or 2013")]
        [ValidateSet(2010,2012,2013)]
        [int]$version
    )
    $VS_VERSION = @{ 2010 = "10.0"; 2012 = "11.0"; 2013 = "12.0" }
    $targetDir = "c:\Program Files (x86)\Microsoft Visual Studio $($VS_VERSION[$version])\VC"
    if (!(Test-Path (Join-Path $targetDir "vcvarsall.bat"))) {
        "Error: Visual Studio $version not installed"
        return
    }
    pushd $targetDir
    cmd /c "vcvarsall.bat&set" |
    foreach {
      if ($_ -match "(.*?)=(.*)") {
        Set-Item -force -path "ENV:\$($matches[1])" -value "$($matches[2])"
      }
    }
    popd
    write-host "`nVisual Studio $version Command Prompt variables set." -ForegroundColor Yellow
}

Keith 已經提到了 PowerShell Community Extensions (PSCX) 及其Invoke-BatchFile命令:

Invoke-BatchFile "${env:ProgramFiles(x86)}\Microsoft Visual Studio 12.0\VC\vcvarsall.bat"

我還注意到 PSCX 還有一個Import-VisualStudioVars函數:

Import-VisualStudioVars -VisualStudioVersion 2013

感謝 Andy S 的回答。 我一直在使用他的解決方案一段時間,但今天遇到了一個問題。 任何帶有等號的值都會在等號處被截斷。 例如,我有:

JAVA_TOOL_OPTIONS=-Duser.home=C:\Users\Me

但我的 PS 會話報告:

PS C:\> $env:JAVA_TOOL_OPTIONS
-Duser.home

我通過將我的配置文件腳本修改為以下內容來解決此問題:

pushd 'c:\Program Files (x86)\Microsoft Visual Studio 11.0\VC'
cmd /c "vcvarsall.bat&set" |
foreach {
  if ($_ -match "=") {
    $i = $_.indexof("=")
    $k = $_.substring(0, $i)
    $v = $_.substring($i + 1)
    set-item -force -path "ENV:\$k"  -value "$v"
  }
}
popd

對於在 2020 年和 Visual Studio Code 1.41.1 中仍在苦苦掙扎的人來說,這里有點跑題了。

使用來自上面和互聯網的所有不同部分的代碼,例如來自https://help.appveyor.com/discussions/questions/18777-how-to-use-vcvars64bat-from-powershell並通過一步一步的方法我設法有下面的腳本工作。

保存到 VSCode“settings.json”並安裝了 Code Runner 擴展。

使用來自 Visual Studio 2015/14.0 的 Microsoft (R) C/C++ 優化編譯器版本“cl.exe”:

"code-runner.runInTerminal": true,
"code-runner.executorMap": {
  "cpp": "cd $dir; pushd \"C:\\Program Files (x86)\\Microsoft Visual Studio 14.0\\VC\"; cmd.exe /c \"call vcvarsall.bat x86_amd64 & set > %temp%\\vcvars.txt\"; Get-Content \"$env:temp\\vcvars.txt\" | Foreach-Object { if ($_ -match \"^(.*?)=(.*)$\") {   Set-Content \"env:\\$($matches[1])\" $matches[2]  }}; popd; cls; cl *.cpp; .\\\"$fileNameWithoutExt.exe\"; Write-Host -NoNewLine 'Press any key to continue...';  $null = $Host.UI.RawUI.ReadKey('NoEcho,IncludeKeyDown'); del \"$fileNameWithoutExt.exe\"; del \"$fileNameWithoutExt.obj\""}

使用來自 Visual Studio 2019/16.4.3 的 Microsoft (R) C/C++ 優化編譯器版本“cl.exe”:

"code-runner.runInTerminal": true,
"code-runner.executorMap": {
  "cpp": "cd $dir; pushd \"c:\\Program Files (x86)\\Microsoft Visual Studio\\2019\\Community\\VC\\Auxiliary\\Build\"; cmd.exe /c \"call vcvarsall.bat x86_amd64 & set > %temp%\\vcvars.txt\"; Get-Content \"$env:temp\\vcvars.txt\" | Foreach-Object { if ($_ -match \"^(.*?)=(.*)$\") {   Set-Content \"env:\\$($matches[1])\" $matches[2]  }}; popd; cls; cl *.cpp; .\\\"$fileNameWithoutExt.exe\"; Write-Host -NoNewLine 'Press any key to continue...';  $null = $Host.UI.RawUI.ReadKey('NoEcho,IncludeKeyDown'); del \"$fileNameWithoutExt.exe\"; del \"$fileNameWithoutExt.obj\""}

HTH

作為上述 Andy S 回答的擴展,這是針對 VS 2019 社區的更新。 但是,我還需要64位,所以這包括-arch=amd64-host_arch=amd64標志以及任何人都需要它們。

pushd "C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\Common7\Tools"
cmd /c "VsDevCmd.bat -arch=amd64 -host_arch=amd64&set " |
foreach {
  if ($_ -match "=") {
    $v = $_.split("="); set-item -force -path "ENV:\$($v[0])"  -value "$($v[1])"
  }
}
popd
Write-Host "`nVisual Studio 2019 Command Prompt variables set." -ForegroundColor Yellow

我喜歡將命令傳遞到子 shell 中,如下所示:

cmd /c "`"${env:VS140COMNTOOLS}vsvars32.bat`" && <someCommand>"

或者替代地

cmd /c "`"${env:VS140COMNTOOLS}..\..\VC\vcvarsall.bat`" amd64 && <someCommand> && <someOtherCommand>"  

以下命令適用於我( Windows 10 | MS Build Tools 16.9.5 | PowerShell 5.1.19041 , 7.1.3 )。 從 PS 運行:

Import-Module 'C:\Program Files (x86)\Microsoft Visual Studio\2019\BuildTools\Common7\Tools\Microsoft.VisualStudio.DevShell.dll'; Enter-VsDevShell 1652063a -DevCmdArguments '-arch=x64'

或者您可以使用以下target創建快捷方式:

<path to your powershell.exe> -noe -c "&{Import-Module """C:\Program Files (x86)\Microsoft Visual Studio\2019\BuildTools\Common7\Tools\Microsoft.VisualStudio.DevShell.dll"""; Enter-VsDevShell 1652063a -DevCmdArguments '-arch=x64'}"

顯然,如果您需要 x86 工具集,請刪除-arch=x64

事實上,我們有一個簡單而干凈的方法來做到這一點。

眾所周知,shell中啟動的子shell會自動繼承父shell的變量。 因此,我們只需要在PowerShell中啟動CMD,執行vcvars64.bat,在這個CMD中再次啟動PowerShell即可。

對於 Visual Studio 2019:

cmd /K '"C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\VC\Auxiliary\Build\vcvars64.bat" && powershell.exe'

如果您使用的是 PowerShell Core:

cmd /K '"C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\VC\Auxiliary\Build\vcvars64.bat" && pwsh.exe'

您可以將其包裝為一個函數並將其放入Powershell 配置文件中(所有用戶的$PSHOME\\Microsoft.PowerShell_profile.ps1 ):

function vcvars64 {
  cmd /K '"C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\VC\Auxiliary\Build\vcvars64.bat" && powershell.exe'
}

或者,如果您使用的是 PowerShell Core:

function vcvars64 {
  cmd /K '"C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\VC\Auxiliary\Build\vcvars64.bat" && pwsh.exe'
}

然后只需在 PowerShell 中執行vcvars64

PS C:\Users\Glavo> cl
cl: The term 'cl' is not recognized as a name of a cmdlet, function, script file, or executable program.
Check the spelling of the name, or if a path was included, verify that the path is correct and try again.
PS C:\Users\Glavo> vcvars64
**********************************************************************
** Visual Studio 2019 Developer Command Prompt v16.11.5
** Copyright (c) 2021 Microsoft Corporation
**********************************************************************
[vcvarsall.bat] Environment initialized for: 'x64'
PowerShell 7.1.5
Copyright (c) Microsoft Corporation.

https://aka.ms/powershell
Type 'help' to get help.

PS C:\Users\Glavo> cl
Microsoft (R) C/C++ Optimizing Compiler Version 19.29.30136 for x64
Copyright (C) Microsoft Corporation.  All rights reserved.

usage: cl [ option... ] filename... [ /link linkoption... ]

代替

  1. 調用批處理腳本
  2. 寫下環境變量
  3. 以如此復雜的方式執行修改,使用 Visual Studio 2022(可能還有 2019),您可以使用以下更簡單的方法
Import-Module "VS-Directory\Community\Common7\Tools\Microsoft.VisualStudio.DevShell.dll"
Enter-VsDevShell -VsInstallPath "VS-Directory\Community" -DevCmdArguments

但是,如果您希望默認情況下為 VS 使用 64 位 MSVC 和環境,則可以使用帶有 arch=64 的 DevCmdArguments

Enter-VsDevShell -VsInstallPath "VS-Directory\Community" -DevCmdArguments '-arch=x64'

使用“模塊”和VsDevShell更加簡單和干凈。 一個簡單的 Powershell 腳本如下,適用於 MSVC 和 Clang:

param(
    [String] $Compiler = "MSVC"
)

if ($Compiler -ne "MSVC" -and $Compiler -ne "Clang") {
    Write-Error "Unknown compiler '$Compiler'; must be MSVC or Clang"
    Exit -1
}

Write-Host "======================================="
Write-Host "Setting up environment variables..."

# Visual Studio path <https://github.com/microsoft/vswhere/wiki/Find-VC>
$vsPath = &"${env:ProgramFiles(x86)}\Microsoft Visual Studio\Installer\vswhere.exe" -latest -products * -requires Microsoft.VisualStudio.Component.VC.Tools.x86.x64 -property installationpath

Write-Host "Microsoft Visual Studio path = '$vsPath'"

# Use module `Microsoft.VisualStudio.DevShell.dll`
Import-Module (Get-ChildItem $vsPath -Recurse -File -Filter Microsoft.VisualStudio.DevShell.dll).FullName

Enter-VsDevShell -VsInstallPath $vsPath -SkipAutomaticLocation -DevCmdArguments '-arch=x64'

# NOTE: `-DevCmdArguments` are arguments to `vsdevcmd.bat`

# Select compiler
if ($Compiler -eq "MSVC") {
    $_Compiler = "MSVC"
    Set-Item -Path "env:CC" -Value "cl.exe"
    Set-Item -Path "env:CXX" -Value "cl.exe"
}
elseif ($Compiler -eq "Clang") {
    $_Compiler = "Clang"
    Set-Item -Path "env:CC" -Value "clang-cl.exe"
    Set-Item -Path "env:CXX" -Value "clang-cl.exe"
}

Write-Host "Selecting $_Compiler as C/C++ compiler."
Write-Host "======================================="

嘗試 powershell 模塊posh-vsdev 它甚至似乎支持多個已安裝的 Visual Studio 版本。

Install-Module -Name posh-vsdev -Scope CurrentUser

# Import the posh-vsdev module module
Import-Module posh-vsdev

# Get all installed Visual Studio instances
Get-VisualStudioVersion

# Get a specific version
Get-VisualStudioVersion -Version 14

# Use the Developer Command Prompt Environment
Use-VisualStudioEnvironment

# Restore the non-Developer environment
Reset-VisualStudioEnvironment

# Reset cache of Visual Studio instances
Reset-VisualStudioVersionCache

# Add posh-vsdev to your PowerShell profile
Add-VisualStudioEnvironmentToProfile -UseEnvironment

使用開發工具環境啟動任何最新的 PowerShell:

C:/Program Files/PowerShell/7/pwsh.exe -noe -c "&{Import-Module """C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\Common7\Tools\Microsoft.VisualStudio.DevShell.dll"""; Enter-VsDevShell 5f8ef82b}" 

如果它不起作用,請通過快速啟動菜單搜索尋找Developer PowerShell for VS 2019 -> 右鍵單擊屬性-> 復制目標行 -> 將 exe 路徑更改為所需的 PowerShell.exe

也可以像您選擇的編輯器/IDE 那樣啟動它 vscode 示例:

"terminal.integrated.profiles.windows": {
"win_dev_shell_64": {
  "path": "C:/Program Files/PowerShell/7/pwsh.exe",
  "args": [
    "-noe",
    "-c",
    "&{Import-Module \"C:\\Program Files (x86)\\Microsoft Visual Studio\\2019\\Community\\Common7\\Tools\\Microsoft.VisualStudio.DevShell.dll\"; Enter-VsDevShell 5f8ef82b}"
    ]
  }
},
"terminal.integrated.defaultProfile.windows": "win_dev_shell_64",

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM