Visual Studio 명령 프롬프트에서 PowerShell을 사용하는 방법은 무엇입니까?
베타 2를 사용한 지 꽤 됐는데 cmd로 팬트해야 한다는 게 너무 짜증나네요.exe 명령 프롬프트를 실행합니다.이전에는 Visual Studio 2008용 vsvars2008.ps1 스크립트를 사용하고 있었습니다.vsvars2010.ps1 스크립트 같은 것이 있습니까?
블로그 포스트 Replace Visual Studio Command Prompt를 PowerShell로 교체하여 이 기능을 충분히 활용할 수 있었습니다.저는 제 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\에 있는 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.batVisual 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
또한 환경 변수 이름과 값의 구분자이기도 한 등호를 포함하여 값이 끊어지지 않도록 분할에서 두 항목만 생성하도록 할 수도 있습니다.
$v = $_.split("=", 2); set-item -force -path "ENV:\$($v[0])" -value
Visual Studio 2022의 마이너 체인지(64비트).
pushd "C:\Program Files\Microsoft Visual Studio\2022\Enterprise\Common7\Tools"
cmd /c "VsDevCmd.bat&set" |
foreach {
if ($_ -match "=") {
$v = $_.split("=", 2); set-item -force -path "ENV:\$($v[0])" -value "$($v[1])"
}
}
popd
Write-Host "`nVisual Studio 2022 Command Prompt variables set." -ForegroundColor Yellow
가장 간단한 옵션은 VS 2010 명령 프롬프트를 실행하고 PowerShell.exe를 시작하는 것입니다."홈" PowerShell 프롬프트에서 이 작업을 수행하려면 이 방법을 사용하십시오.저는 리 홈즈가 예전에 쓴 대본을 사용합니다.
<#
.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 Community Extensions 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"
PowerShell과 비슷하게 보이려면 바로 가기 속성의 색상 탭으로 이동하여 빨간색, 녹색 및 파란색 값을 각각 1, 36 및 86으로 설정합니다.
(a) Visual Studio 2013 지원 제공, (b) 이전 두 답변 중 최상의 답변 결합, (c) 기능 포장지 제공:
이것은 Andy의 테크닉(Andy가 지적한 대로 Allen Mack의 테크닉에 근거하고 있다)에 근거하고 있습니다(이것은 Allen이 지적한 대로 Robert Anderson의 테크닉에 근거하고 있습니다(이 모든 것은, 「me--」라고 하는 유저에 의해서 이 페이지에 기재되어 있기 때문에, 저도 그 점을 고려했습니다).
여기 마지막 코드가 있습니다. 정규식에 포함된 비권한 수량자를 사용하여 값에 포함될 수 있는 모든 값을 처리하십시오.이것은 또한 코드를 단순화할 수 있습니다.Andy의 예에서와 같이 일치한 후 분할하거나 "me--"의 예에서와 같이 일치한 후 하위 문자열과 인덱스를 분할합니다.)
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
}
Push-Location $targetDir
cmd /c "vcvarsall.bat&set" |
foreach {
if ($_ -match "(.*?)=(.*)") {
Set-Item -force -path "ENV:\$($matches[1])" -value "$($matches[2])"
}
}
Pop-Location
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」POS도 되어 있는 을 알 수 .Import-VisualStudioVars★★★★
Import-VisualStudioVars -VisualStudioVersion 2013
Andy S의 답변에 찬사를 보냅니다.한동안 그의 솔루션을 사용했는데 오늘 문제가 생겼어요.등호가 있는 값은 등호에서 잘립니다.예를 들어 다음과 같습니다.
JAVA_TOOL_OPTIONS=-Duser.home=C:\Users\Me
그러나 PowerShell 세션은 다음과 같이 보고했습니다.
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
및 'Modules' 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에서 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'
}
실행해 .vcvars64PowerShell:
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... ]
대신
- 배치 스크립트 호출
- 환경 변수 기록
- 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'
2020년과 Visual Studio Code 1.41.1에서 여전히 어려움을 겪고 있는 분들을 위해, 이것은 다소 주제에서 벗어난 것입니다.
"How can I use vcvars64.bat from PowerShell?" (PowerShell에서 vcvars64.bat을 사용하는 방법)과 같은 이전 답변 및 인터넷과 다른 모든 코드를 사용하여 다음 스크립트를 실행할 수 있었습니다.
Visual Studio 코드 "settings.json"에 저장되며 Code Runner 확장자가 설치되어 있습니다.
Microsoft(R) C/C++ Optimizing 컴파일러 버전 "cl.exe"를 Visual Studio 2015/14.0에서 사용하는 경우:
"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\""}
Microsoft(R) C/C++ Optimizing 컴파일러 버전 "cl.exe"를 Visual Studio 2019/16.4.3에서 사용하는 경우:
"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\""}
Andy S의 답변의 연장선상에서 Visual Studio 2019 Community 에디션으로 업데이트 되었습니다.단, 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
powershell module 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
다음과 같은 명령어를 아이 셸에 전달합니다.
cmd /c "`"${env:VS140COMNTOOLS}vsvars32.bat`" && <someCommand>"
또는 다른 방법으로
cmd /c "`"${env:VS140COMNTOOLS}..\..\VC\vcvarsall.bat`" amd64 && <someCommand> && <someOtherCommand>"
먼저 이 폴더의 내용을 확인합니다.
C:/ProgramData/Microsoft/VisualStudio/Packages/_Instances/
이름이 16진수로 구성된 다른 폴더가 있습니다(예:2a7a9ed6단, MSVC 버전에 따라 다릅니다.라고 부르겠습니다.<instance_id>.
그런 다음 PowerShell에서 실행합니다.
Import-Module 'C:\Program Files (x86)\Microsoft Visual Studio\2019\BuildTools\Common7\Tools\Microsoft.VisualStudio.DevShell.dll'; Enter-VsDevShell <instance_id> -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 <instance_id> -DevCmdArguments '-arch=x64'}"
확실히, 떨어뜨려라-arch=x64x86 툴셋이 필요한 경우
개발 도구를 사용하여 최신 PowerShell을 시작하려면 env:
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}"
그래도 문제가 해결되지 않으면 빠른 시작 메뉴 검색 -> 속성 -> 대상 복사 -> 원하는 PowerShell.exe로 exe 경로를 변경하여 VS용 Developer PowerShell 2019를 찾습니다.
또한 선택한 Editor/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",
언급URL : https://stackoverflow.com/questions/2124753/how-can-i-use-powershell-with-the-visual-studio-command-prompt
'source' 카테고리의 다른 글
| UITableView, 설정 장소 구분 색상 (0) | 2023.04.17 |
|---|---|
| 컨트롤의 속성을 다른 컨트롤의 속성에 바인딩하려면 어떻게 해야 합니까? (0) | 2023.04.17 |
| 앱 내 구매를 iOS 애플리케이션에 추가하려면 어떻게 해야 합니까? (0) | 2023.04.12 |
| WPF 엔트리 포인트 교환 (0) | 2023.04.12 |
| 엑셀의 서브스트링 (0) | 2023.04.12 |
