I am experiencing a very strange behavior, old batch file works well under windows XP. Why doesn't it work when compiling a simple file like hello.c under (Vs2017 + Win10) by a batch file in cmd window?
When realizing that Win10 has new security policy,,I read some articles on Microsoft's website. They recommend using the developer command-line window for command-line compilation.
Indeed, manual operation works well. But when I logged on Win10 as a super administrator and tried to run everything via a batch file,
it didn't work, just finished the environment configuration.
When running the commands in the batch file manually, everything works as expected (executable file successfully generated).
What is wrong with that?
Here is the content of the batch file:
%comspec% /k "C:\Program Files(x86)\Microsoft Visual Studio\2017 \Community\VC\Auxiliary\Build\vcvars64.bat"
cd g:\testdir
g:
cl TestBatFileCompile.c
Preliminary Notes:
vcvars64.bat simply calls vcvarsall.bat and it passes the x64 argument to it, followed by its own (if any)
vcvarsall.bat mainly sets some env vars (set VSCMD_DEBUG=3 prior running it, for verbose output) required for the VStudio build tools to work. Check [MS.Docs]: Build C/C++ code on the command line for more details
I enhanced / simplified your example for more clarity:
script.bat:
#echo off
echo Running vcvars...
%comspec% /K "c:\Install\x86\Microsoft\Visual Studio Community\2017\VC\Auxiliary\Build\vcvarsall.bat" x64
echo Ran vcvars: %ERRORLEVEL%
echo Running cl...
cl /nologo dummy.c /link /NOLOGO
echo Ran cl: %ERRORLEVEL%
dummy.c:
int main() {
return 0;
}
Output:
e:\Work\Dev\StackOverflow\q053523085>dir /b
dummy.c
script.bat
e:\Work\Dev\StackOverflow\q053523085>script.bat
Running vcvars...
**********************************************************************
** Visual Studio 2017 Developer Command Prompt v15.9.2
** Copyright (c) 2017 Microsoft Corporation
**********************************************************************
[vcvarsall.bat] Environment initialized for: 'x64'
e:\Work\Dev\StackOverflow\q053523085>rem HMMM, SOMETHING DOESN'T SEEM QUITE RIGHT. LET'S TRY EXITING CMD...
e:\Work\Dev\StackOverflow\q053523085>exit
Ran vcvars: 0
Running cl...
'cl' is not recognized as an internal or external command,
operable program or batch file.
Ran cl: 9009
What happened?
cmd /K ([MS.Docs]: Cmd) opened a new cmd instance, on top of the existing one (using the same window)
vcvarsall was called in this (2nd) instance, did its job and finished, and things seem to have been left in the air
But after typing exit, it turns out that cl did run, but in the 1st cmd instance (in the background, if you will), and since the variables were not previously set by vcvarsall, it failed
To make things work, invoke vcvarsall using [MS.Docs]: call:
call "c:\Install\x86\Microsoft\Visual Studio Community\2017\VC\Auxiliary\Build\vcvarsall.bat" x64
Output (in a new cmd window):
e:\Work\Dev\StackOverflow\q053523085>dir /b
dummy.c
script.bat
e:\Work\Dev\StackOverflow\q053523085>script.bat
Running vcvars...
**********************************************************************
** Visual Studio 2017 Developer Command Prompt v15.9.2
** Copyright (c) 2017 Microsoft Corporation
**********************************************************************
[vcvarsall.bat] Environment initialized for: 'x64'
Ran vcvars: 0
Running cl...
dummy.c
Ran cl: 0
e:\Work\Dev\StackOverflow\q053523085>dir /b
dummy.c
dummy.exe
dummy.obj
script.bat
I am unable to use the cl command in PowerShell.
I tried to add the following command to my PowerShell profile to exec vcbuildtools.bat, but PowerShell does not recognize cl command on PowerShell?
&"C:\Program Files (x86)\Microsoft Visual C++ Build Tools\vcbuildtools.bat"
OS: Windows 10
Just to be clear I'm addressing the asker's issue that cl is not in the PATH even after running this in PowerShell
&"C:\Program Files (x86)\Microsoft Visual C++ Build Tools\vcbuildtools.bat"
I think this boils down to the issue that batch file can't export variables to PowerShell (also related: this question), as you've found out with vcbuildtools.bat. I think it's because PowerShell invokes a cmd.exe subshell to execute the batch file which changes the environment in the subshell but the changes don't propagate to the parent shell i.e. PowerShell.
Solution 1
One way is to use the fact that subshell inherits the environment from the parent shell. So if you run this in PowerShell, the environment set by the batch file is preserved
cmd.exe /k "C:\Program Files (x86)\Microsoft Visual C++ Build Tools\vcbuildtools.bat" `& powershell
Take note of `&. The character has to be escaped because it has a special meaning in PowerShell.
Solution 2
The Pscx module has an Import-VisualStudioVars function which imports environment variables for Visual Studio. An example usage is
Import-VisualStudioVars 2015 amd64
if you're using VS/BuildTools 2015 and compiling 64-bit programs. You can use Pop-EnvironmentBlock to revert the changes. See man Import-VisualStudioVars -full for more information.
Alternatively, Pscx also has an Invoke-BatchFile function that retains environment changes by a batch file. An example usage
Invoke-BatchFile "C:\Program Files (x86)\Microsoft Visual C++ Build Tools\vcbuildtools.bat"
See man Invoke-Batchfile -full for more information.
Notes
To download the up-to-date version of Pscx from PowerShell gallery, you will need PowerShellGet which is shipped with PowerShell 5 and is available as a downloadable installer for PowerShell 3 and 4.
For those with PowerShell 1 and 2, older versions of Pscx is available on Codeplex.
You can use the following function to invoke a cmd.exe shell script (batch file) and persist its environment variables:
function Invoke-CmdScript {
param(
[String] $scriptName
)
$cmdLine = """$scriptName"" $args & set"
& $env:SystemRoot\system32\cmd.exe /c $cmdLine |
Select-String '^([^=]*)=(.*)$' | ForEach-Object {
$varName = $_.Matches[0].Groups[1].Value
$varValue = $_.Matches[0].Groups[2].Value
Set-Item Env:$varName $varValue
}
}
Add this function to your PowerShell profile, and run the batch file using the function:
Invoke-CmdScript "C:\Program Files (x86)\Microsoft Visual Studio 14.0\Common7\Tools\vsvars32.bat"
Fortunately, VS 2019 Community now has a Developer PowerShell for VS 2019 command.
The actual command, if you want to see the properties for the shortcut, is rather verbose.
C:\Windows\SysWOW64\WindowsPowerShell\v1.0\powershell.exe -noe -c "&{Import-Module """C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\Common7\Tools\Microsoft.VisualStudio.DevShell.dll"""; Enter-VsDevShell 14bbfab9}"
Anyway, I am using this and it adds the right cl.exe to my path, but there is an odd message after running it:
C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\VC\Tools\MSVC\14.23.28105\include\ostream(750): warning C4530: C++ exception handler used, but unwind semantics are not enabled. Specify /EHsc
.\hey.cpp(4): note: see reference to function template instantiation 'std::basic_ostream<char,std::char_traits<char>> &std::operator <<<std::char_traits<char>>(std::basic_ostream<char,std::char_traits<char>> &,const char *)' being compiled
Another option from PowerShell gallery:
posh-vs
Makes Visual Studio command line tools available in PowerShell. Supports Visual Studio 2017 and 2015.
I also encountered the same problem, type cmd.exe and you'll change control to command line.
PowerShell example
If you want to go back to PowerShell, no problem. Just write exit. As simple as it sounds
The environment is set as:
#echo off
call "C:\Program Files (x86)\Microsoft Visual Studio12.0\Common7\Tools\VsDevCmd.bat"
call "C:\Program Files (x86)\Microsoft Visual Studio 12.0\VC\vcvarsall.bat" amd64
e:
cd E:\Wireshark_Plugin\Source\wireshark-master
set YES_I_KNOW_ABOUT_THE_DEPRECATION=1
set VISUALSTUDIOVERSION=12.0
set MSVC_VARIANT=MSVC2013EE
set CYGWIN_PATH=E:\Software\Cygwin\bin
set WIRESHARK_BASE_DIR=E:\Wireshark_Plugin\Source\wireshark-master
set WIRESHARK_TARGET_PLATFORM=win64
set QT5_BASE_DIR=E:\Software\QT\5.6\msvc2013_64
::nmake -f Makefile.nmake verify_tools
::nmake -f Makefile.nmake setup
::nmake -f Makefile.nmake distclean
nmake -f Makefile.nmake all
pause
The compile result shown below failed
Microsoft (R) Program Maintenance Utility Version 12.00.21005.1
Copyright (C) Microsoft Corporation. All rights reserved.
cd ..
xcopy E:\Wireshark_Plugin\Source\wireshark-master\Wireshark-win64-libs\zlib-1.2.8-ws zlib.tmp /D /I /E /Y
cd zlib.tmp
"C:\Program Files (x86)\Microsoft Visual Studio 12.0\VC\BIN\nmake.exe" /
-f win32/Makefile.msc zlib1.dll AS=ml64 LOC="-I. -DASMV -DASMINF" OBJA="inffasx64.obj gvmat64.obj inffas8664.obj"
Microsoft (R) Program Maintenance Utility Version 12.00.21005.1
Copyright (C) Microsoft Corporation. All rights reserved.
ml64 -c -coff -Zi -I. -DASMV -DASMINF ./contrib/masmx64\inffasx64.asm
'ml64' is not internal or external command
NMAKE : fatal error U1077: 'ml64' : return code '0x1'
Stop.
NMAKE : fatal error U1077: '"C:\Program Files (x86)\Microsoft Visual Studio 12.0\VC\BIN\nmake.exe"' : return code '0x2'
Stop.
Does anybody has the same problem as me? I was confused about for almost one week, hope someone may help me.
Thanks all.
By the way, it has compiled successfully under 32bit option.
Then environment setting is as below:
call "C:\Program Files (x86)\Microsoft Visual Studio 12.0\VC\bin\vcvars32.bat"
e:
cd E:\Wireshark_Plugin\Source\wireshark-master
set YES_I_KNOW_ABOUT_THE_DEPRECATION=1
set VISUALSTUDIOVERSION=12.0
set MSVC_VARIANT=MSVC2013EE
set CYGWIN_PATH=E:\Software\Cygwin\bin
set WIRESHARK_BASE_DIR=E:\Wireshark_Plugin\Source\wireshark-master
set WIRESHARK_TARGET_PLATFORM=win32
set QT5_BASE_DIR=E:\Software\QT\5.6\msvc2013_64
call "C:\Program Files (x86)\Microsoft Visual Studio 12.0\VC\vcvarsall.bat" x86
::nmake -f Makefile.nmake verify_tools
::nmake -f Makefile.nmake setup
::nmake -f Makefile.nmake distclean
nmake -f Makefile.nmake all
pause
Thanks you all for paying attention my question.I have resolved this issue.
It seems the Unicode setting problem.
Go to Control Panel->Region and Language->Language for the non-Unicode programs
In "Current language for non-Unicode programs", Change to "English(United States)".
In a serious intiative to migrate all my command line operations to PowerShell, I would like to avoid using the old fashioned command console for anything. However, the Visual Studio Command prompt has various environment variables and path settings not found in the default command prompt. How could I create a 'Visual Studio PowerShell' with those same settings?
You can use for example this script to import Visual Studio command prompt environment, see the examples in the script documentation comments, e.g. for Visual Studio 2010:
Invoke-Environment '"%VS100COMNTOOLS%\vsvars32.bat"'
Having done that in the beginning of a PowerShell session (from your profile or manually), you get what you ask for in this PowerShell session.
Or you can use the solution provided by Keith Hill in this answer.
have a look at PowerConsole
PowerConsole has been incorporated into NuGet http://nuget.codeplex.com/. You get PowerShell inside Visual Studio and a package management system.
I use this script that I call Initialize-VisualStudio.ps1, i call it in my profile with dot source, to set the environment variables need it, in my actual session:
param([switch]$ArquitectureX86)
if($ArquitectureX86)
{ $arq= "x86"}
else
{ $arq="x64"}
pushd 'c:\Program Files (x86)\Microsoft Visual Studio 10.0\VC'
cmd /c "vcvarsall.bat $arq&set" |
foreach {
if ($_ -match "=") {
$v = $_.split("="); set-item -force -path "ENV:\$($v[0])" -value "$($v[1])";
}
}
popd
What I do is create a simple cmd batch command script that looks like this:
call "%VS80COMNTOOLS%vsvars32.bat"
powershell
Then I create a shortcut that invokes this through cmd. The shortcut target looks like:
%windir%\System32\cmd.exe /k "SetupPSBuildEnvironment.cmd"
If you want the console to look like the powershell console, just modify the Layout to your liking in the shortcut properties.
First, check the contents of this folder:
C:/ProgramData/Microsoft/VisualStudio/Packages/_Instances/
There'll be another folder in it with a name consisting of hex digits (e.g. 2a7a9ed6, but that will vary for different MSVC versions). I'll refer to it as <instance_id>.
Then run from PS:
Import-Module 'C:\Program Files (x86)\Microsoft Visual Studio\2019\BuildTools\Common7\Tools\Microsoft.VisualStudio.DevShell.dll'; Enter-VsDevShell <instance_id> -DevCmdArguments '-arch=x64'
Or you can create a shortcut with the following 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'}"
Obviously, drop -arch=x64 if you need x86 toolset.
Works for me on Windows 10 with MS Build Tools 16.9.5 and PowerShell 5.1.19041,7.1.3
I've been using Beta 2 for a while now and it's been driving me nuts that I have to punt to cmd.exe when running the Visual Studio 2010 Command Prompt. I used to have a nice vsvars2008.ps1 script for Visual Studio 2008. Is there a vsvars2010.ps1 script or something similar?
Stealing liberally from blog post Replace Visual Studio Command Prompt with PowerShell, I was able to get this to work. I added the following to my profile.ps1 file and all is well with the world.
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
This has worked well for years - until Visual Studio 2015. vcvarsall.bat no longer exists. Instead, you can use the vsvars32.bat file, which is located in the Common7\Tools folder.
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
Things have changed yet again for Visual Studio 2017. vsvars32.bat appears to have been dropped in favor of VsDevCmd.bat. The exact path may vary depending on which edition of Visual Studio 2017 you're using.
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
You can also make the split create just two items to avoid breaking values including the equal sign, which is also the separator of the environment variable name and the value:
$v = $_.split("=", 2); set-item -force -path "ENV:\$($v[0])" -value
Minor Changes for Visual Studio 2022, now that it's 64-bit.
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
The simplest option is to run the VS 2010 command prompt and then start PowerShell.exe. If you really want to do this from your "home" PowerShell prompt, the approach you show is the way to go. I use a script that Lee Holmes wrote a while back:
<#
.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
}
Note: this function will be available in the PowerShell Community Extensions 2.0 module-based release coming soon.
I found a simple method here: modify the shortcut.
The original shortcut is something like this:
%comspec% /k ""C:\Program Files (x86)\Microsoft Visual Studio 12.0\Common7\Tools\VsDevCmd.bat""
Add & powershell before the last quote, like this:
%comspec% /k ""C:\Program Files (x86)\Microsoft Visual Studio 12.0\Common7\Tools\VsDevCmd.bat" & powershell"
If you want to make it look more like PowerShell, go to the Colors tab of the shortcut properties and set the Red, Green and Blue values to 1, 36 and 86 respectively.
To (a) provide Visual Studio 2013 support; (b) combine the best of two previous answers; and (c) provide a function wrapper:
This builds on Andy's technique (which builds on Allen Mack's technique as Andy indicated (which in turn builds on Robert Anderson's technique as Allen indicated (all of which had a slight glitch as indicated on this page by the user known only as "me--", so I took that into account as well))).
Here is my final code--note the use of the non-greedy quantifier in the regex to handle any possible embedded equals in the values. That also happens to simplify the code: a single match instead of a match then split as in Andy's example or a match then indexof and substrings as in "me--"'s example).
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 has already mentioned PowerShell Community Extensions (PSCX), with its Invoke-BatchFile command:
Invoke-BatchFile "${env:ProgramFiles(x86)}\Microsoft Visual Studio 12.0\VC\vcvarsall.bat"
I also noticed that PSCX also has an Import-VisualStudioVars function:
Import-VisualStudioVars -VisualStudioVersion 2013
Kudos to Andy S for his answer. I've been using his solution for a while, but I ran into a problem today. Any value that has an equals sign in it is truncated at the equals sign. For example, I had:
JAVA_TOOL_OPTIONS=-Duser.home=C:\Users\Me
But my PowerShell session reported:
PS C:\> $env:JAVA_TOOL_OPTIONS
-Duser.home
I fixed this by modifying my profile script to the following:
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
Using 'Modules' and VsDevShell is much simpler and cleaner. A simple Powershell script is the following which works for MSVC and 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 "======================================="
In fact, we have a simple and clean way to do it.
As we all know, the child shell launched in the shell automatically inherits the variables of the parent shell. Therefore, we only need to start CMD in PowerShell, execute vcvars64.bat, and start PowerShell again in this CMD.
For Visual Studio 2019:
cmd /K '"C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\VC\Auxiliary\Build\vcvars64.bat" && powershell.exe'
If you are using PowerShell Core:
cmd /K '"C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\VC\Auxiliary\Build\vcvars64.bat" && pwsh.exe'
You can wrap it as a function and put it in Powershell Profiles ($PSHOME\Microsoft.PowerShell_profile.ps1 for all users):
function vcvars64 {
cmd /K '"C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\VC\Auxiliary\Build\vcvars64.bat" && powershell.exe'
}
Or if you are using PowerShell Core:
function vcvars64 {
cmd /K '"C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\VC\Auxiliary\Build\vcvars64.bat" && pwsh.exe'
}
Then simply execute vcvars64 in PowerShell:
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... ]
Instead of
Calling the Batch script
Writing the environment variables down
Performing modifications in so complicated a way, with Visual Studio 2022 (and probably 2019), you can use the following much more simpler approach
Import-Module "VS-Directory\Community\Common7\Tools\Microsoft.VisualStudio.DevShell.dll"
Enter-VsDevShell -VsInstallPath "VS-Directory\Community" -DevCmdArguments
If however, you wish to use 64 bit MSVC and environment by default for VS, you can use the DevCmdArguments with arch=64
Enter-VsDevShell -VsInstallPath "VS-Directory\Community" -DevCmdArguments '-arch=x64'
For someone who is still struggling with it in 2020 and Visual Studio Code 1.41.1, so this is a bit off-topic here.
Using all different parts of code from previous answers and the Internet, e.g., from How can I use vcvars64.bat from PowerShell? and with a step by step approach I managed to have the below script working.
Saved into Visual Studio Code "settings.json" and with the Code Runner extension installed.
With Microsoft (R) C/C++ Optimizing Compiler Version "cl.exe" from 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\""}
With Microsoft (R) C/C++ Optimizing Compiler Version "cl.exe" from 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\""}
As an extension to Andy S's answer, this is updated for Visual Studio 2019 Community edition. However, I also needed 64-bit, so this includes the -arch=amd64 and -host_arch=amd64 flags as well for anyone that needs them.
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
Try powershell module posh-vsdev. It even seems to have support for multiple installed versions of 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
I like to pass the commands into a child shell like so:
cmd /c "`"${env:VS140COMNTOOLS}vsvars32.bat`" && <someCommand>"
Or alternatively
cmd /c "`"${env:VS140COMNTOOLS}..\..\VC\vcvarsall.bat`" amd64 && <someCommand> && <someOtherCommand>"
First, check the contents of this folder:
C:/ProgramData/Microsoft/VisualStudio/Packages/_Instances/
There'll be another folder in it with a name consisting of hex digits (e.g. 2a7a9ed6, but that will vary for different MSVC versions). I'll refer to it as <instance_id>.
Then run from 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'
Or you can create a shortcut with the following 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'}"
Obviously, drop -arch=x64 if you need the x86 toolset.
To start any latest PowerShell with dev tools 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}"
If it doesn't work look for Developer PowerShell for VS 2019 via quick start menu search -> right-click properties -> copy target line -> change exe path to desired PowerShell.exe
Can also start it like that for your Editor/IDE of choice
Example for 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",