Msbuild exe где лежит
Перейти к содержимому

Msbuild exe где лежит

  • автор:

Msbuild exe где лежит

MSBuild is usually shipped with .NET or Visual Studio. It’s location may vary from users to users (fuck you Microsoft) and unfortunately, you have to figure that out yourself by googling the shit out of it. Here are a few location where you might be lucky to find it:

  • C:\Windows\Microsoft.NET\Framework64\v4.0.30319\MSBuild.exe
  • C:\Program Files (x86)\Microsoft Visual Studio\2017\BuildTools\MSBuild\15.0\Bin

How the fuck do I add msbuild to my freaking PATH?

Once you’ev found the path to MSBuild.exe, you need to add its path to the PATH environment variable so that you can use it in your terminal (the «terminal», the forbidden word for Microsoft idiots). Though it is in theory possible to set that PATH in the terminal with commands such as SETX or SET , there might a myriad of reasons where this would not work. The safest way to do it is the stupid Windows manual way:

  1. Open the control panel.
  2. Click on System and Security and then on System.
  3. In the left pane, click on Advanced system settings.
  4. At the very bottom of the pop up, click on Environment Variables
  5. Edit the Path variable and append the folder’s path that contains the MSBuild.exe to it (e.g., ;C:\Windows\Microsoft.NET\Framework64\v4.0.30319\ . Notice the use of ; to separate each path).

Hello world CSPROJ file

MSBuild uses .csproj file to figure out what to do. The key concepts to grasps are:

  • Target : A target is the XML block that defines the series of steps to follow.
  • PropertyGroup : The property group are a way to define variables as well as conditional variables. Each property group defines one of more variables. They are executed sequentially to enable conditions (more about this later in the Configuring different MSBuild workflows with the CSPROJ and the PropertyGroup section).

Let’s have a look to this following example:

my_proj.csproj

This should return something similar to:

As you can see, we hard-coded the text Hello and World and we used a variable ProjectDir set to Hello in the property group.

It is possible to overide the ProjectDir variable as follow:

Configuring different MSBuild workflows with the CSPROJ and the PropertyGroup

The following example shows the use of the Condition directive to set the Environment based on the value of the ProjectDir .

How to check the .NET version?

How to package your project?

  1. Build your project using a specific configuration ( -p:Configuration=Release ).
  2. Package it ( -t:Package ) under C:\package\your_project ( -p:_PackageTempDir=C:\package\your_project ).
  3. Zip the package to a specific location ( -p:PackageLocation=C:\package_zip\your_project.zip ).

WARNING: The zip folder structure mimics the path defined under _PackageTempDir (in our example, the folder structure will be Content\C_C\package\your_project ). There is no straighforward way to fix this.

How to check the msbuild version?

How to restore packages?

This has actually nothing to do with msbuild, but that’s such a common requirement that we decided to document it. It assumes that you have the nuget.exe under source control in your project.

Visual Studio uses certain reserved names for its csproj variables. The list below is an exhaustive list. Those reserved variable names are referred as macro.

Using command-line MSBuild tool to build .Net Project/Solution

In this post, I will walk you through on how you can use command-line MSBuild tool to build a .net solution or project.

Basic Info from MSBuild GitHub page:

The Microsoft Build Engine is a platform for building applications. This engine, which is also known as MSBuild, provides an XML schema for a project file that controls how the build platform processes and builds software. Visual Studio uses MSBuild, but MSBuild does not depend on Visual Studio. By invoking msbuild.exe on your project or solution file, you can orchestrate and build products in environments where Visual Studio isn’t installed.

It is a handy tool for build servers. Usually, you would want to avoid bloating build-server with the whole Visual Studio installation. Instead, you can leverage the MSBuild command-line tool to build your application. Following are few ways you can use msbuild.exe

Prerequisites:

Optional: you could add MSBuild location to your System Environments Variable for easy access.

You can find the MSBuild exe in

Build a solution:
Build a specific project

The project could be c# or vb or any other .Net compatible project.

Both of the above commands will build a debug version of your solution/project. What if you want to specify Release Configuration or other Configuration you created?

Где находится MSBuild.exe установлен в Windows при установке с помощью BuildTools Full.exe?

Я пытаюсь настроить сервер сборки для .NET, но не могу понять, где MSBuild.exe установлен.

Я пытаюсь установить MSBuild с помощью Microsoft Build Tools 2013: https://www.microsoft.com/en-us/download/details.aspx?id=40760

2 ответов

MSBuild в предыдущих версиях .NET Framework был установлен с ним, но они решили установить его с Visual Studio или с пакетом BuildTools_Full.исполняемый.

путь для установки .NET framework C:\Windows\Microsoft.NET\Framework[64 или пустой][framework_version] Путь при установке Visual Studio-это является C:\Program файлы (для x86)\MSBuild в[Версия]\bin для x86 и файлы C:\Program (для x86)\MSBuild в[Версия]\Бин\amd64 для 64-разрядных.

путь, когда BuildTools_Full.exe установлен так же, как при установке MSBuild с Visual Studio.

MSBuild теперь устанавливается в папку под каждой версией Visual Studio. Например, C:\Program Files (x86)\Microsoft Visual Studio17\Enterprise\MSBuild . Вы также можете использовать следующий модуль PowerShell для поиска MSBuild:vssetup.в PowerShell.

MSBuild больше не устанавливается в глобальный кэш сборок. Чтобы программно ссылаться на MSBuild, используйте NuGet пакеты.

Путь к MSBuild

Как я могу программно получить путь к MSBuild с машины, на которой запущен мой .exe?

Я могу получить версию .NET из среды, но есть ли способ получить правильную папку для версии .NET?

22 ответы

Ковыряется в реестре, похоже

может быть то, что вам нужно; запустите regedit.exe и посмотрите.

Запрос через командную строку (на Николай Ботев)

Запрос через PowerShell (на МовГП0)

Я установил Visual Studio 2017 RC и запустил командную строку разработчика, версия MSBuild — 15. +, но эта версия не отображается в реестре. Как мне получить доступ к тому же MSBuild, который использует Dev Cmd Prompt? — СуперДжМН

MSBuild 15 находится в `C: \ Program Files (x86) \ Microsoft Visual Studio \ 2017 \ Enterprise \ MSBuild \ 15.0 \ Bin \ amd64` — Зевс

Только если вы установили туда VS2017, я не смог найти ни одной точки входа в реестр для MsBuildToolsPath для набора инструментов 15.0 — Пацив

docs.microsoft.com/en-us/visualstudio/msbuild/… «MSBuild теперь установлен в папке для каждой версии Visual Studio. Например, C: \ Program Files (x86) \ Microsoft Visual Studio \ 2017 \ Enterprise \ MSBuild» и «Значения ToolsVersion больше не устанавливаются в реестре» — Хулвей

@ORMapper Microsoft предлагает проект на GitHub для определения путей Visual Studio 2017 / msbuild 15.x экземпляры. Это единственный исполняемый файл, который может использоваться вашим программным обеспечением / скриптами сборки. — Рой Дантон

Вы также можете распечатать путь к MSBuild.exe в командной строке:

Обратите внимание: если вы хотите создать приложение для Windows Phone, ему потребуется 32-битный файл msbuild. Запрос реестра дает только 64-битную сборку msbuild на 64-битной машине. — Виктор Ионеску

@VictorIonescu: вы можете использовать /reg:32 or /reg:64 в обоих случаях cmd (или любой другой процесс, который вы выполняете), чтобы явно получить этот путь. — Саймон Бьюкен

это даст вам путь к старому (4.0) месту — тот, который вы, вероятно, хотите, на самом деле находится в другом месте, см. stackoverflow.com/questions/32007871/… — Джонни Раа

В моем случае это было под Computer\HKEY_LOCAL_MACHINE\SOFTWARE\WOW6432Node\Microsoft\MSBuild\ToolsVersions\4.0\MSBuildToolsPath — Сен Джейкоб

Если вы хотите использовать MSBuild для .Net 4, вы можете использовать следующую команду PowerShell, чтобы получить путь к исполняемому файлу. Если вам нужна версия 2.0 или 3.5, просто измените переменную $ dotNetVersion.

Чтобы запустить исполняемый файл, вам нужно добавить к переменной $ msbuild &. Это выполнит переменную.

работает также для $dotNetVersion 12.0 (по сравнению с 2013 годом) и 14.0 (по сравнению с 2015 годом) (если, конечно, установлено) — Джулиан

Не работает для VS 2017, что не добавляет значения под HKLM:\software\Microsoft\MSBuild\ToolsVersions . Вместо этого вам нужно получить установочный каталог VS2017 из HKLM:\SOFTWARE\WOW6432Node\Microsoft\VisualStud‌​io\SxS\VS7\15.0 , затем добавьте MSBuild\15.0\Bin\MSBuild.exe чтобы получить расположение EXE MSBuild. — Ян Кемп

Для сценариев оболочки cmd в Windows 7 я использую следующий фрагмент в своем пакетном файле, чтобы найти MSBuild.exe в .NET Framework версии 4. Я предполагаю, что версия 4 присутствует, но не предполагаю подверсию. Это не совсем универсальное решение, но для быстрых сценариев может быть полезно:

Для моих целей я выхожу из командного файла с ошибкой, если это не сработало:

ответ дан 17 мая ’16, 17:05

@yoyo Что set bb.build.msbuild.exe= для? Это требуется или просто артефакт вашей установки? — Элиза

@ Elisée Упс, извините, это опечатка при копировании / вставке. В своей среде я вызываю переменную bb.build.msbuild.exe, я не позаботился исправить этот экземпляр, когда вставил в ответ. Сейчас исправлено, спасибо, что указали на это. — YOYO

  • PowerShell: &»$\Microsoft Visual Studio\Installer\vswhere.exe» -latest -prerelease -products * -requires Microsoft.Component.MSBuild -find MSBuild\**\Bin\MSBuild.exe
  • CMD: «%ProgramFiles(x86)%\Microsoft Visual Studio\Installer\vswhere.exe» -latest -prerelease -products * -requires Microsoft.Component.MSBuild -find MSBuild\**\Bin\MSBuild.exe
  • PowerShell: &»$\Microsoft Visual Studio\Installer\vswhere.exe» -latest -prerelease -products * -requires Microsoft.VisualStudio.PackageGroup.TestTools.Core -find Common7\IDE\CommonExtensions\Microsoft\TestWindow\vstest.console.exe
  • CMD: «%ProgramFiles(x86)%\Microsoft Visual Studio\Installer\vswhere.exe» -latest -prerelease -products * -requires Microsoft.VisualStudio.PackageGroup.TestTools.Core -find Common7\IDE\CommonExtensions\Microsoft\TestWindow\vstest.console.exe

(Обратите внимание, что приведенные выше инструкции немного отличаются от официальных инструкций Microsoft. В частности, я добавил -prerelease флаг, чтобы разрешить установку Preview и RC, и -products * для обнаружения установок Visual Studio Build Tools.)

Name already in use

visualstudio-docs / docs / msbuild / walkthrough-using-msbuild.md

  • Go to file T
  • Go to line L
  • Copy path
  • Copy permalink
  • Open with Desktop
  • View raw
  • Copy raw contents Copy raw contents

Copy raw contents

Copy raw contents

Walkthrough: Use MSBuild

MSBuild is the build platform for Microsoft and Visual Studio. This walkthrough introduces you to the building blocks of MSBuild and shows you how to write, manipulate, and debug MSBuild projects. You will learn about:

Creating and manipulating a project file.

How to use build properties.

How to use build items.

You can run MSBuild from Visual Studio, or from the Command Window. In this walkthrough, you create an MSBuild project file using Visual Studio. You edit the project file in Visual Studio, and use the Command Window to build the project and examine the results.

. moniker range=»vs-2019″ If you have Visual Studio, then you already have MSBuild installed. With Visual Studio 2019 and later, it’s installed under the Visual Studio installation folder. For a typical default installation on Windows 10, MSBuild.exe is under the installation folder in MSBuild\Current\Bin.

In the installer, make sure MSBuild tools for the workloads you use are selected, and choose Install.

Installing MSBuild

To install MSBuild on a system that doesn’t have Visual Studio, go to Build Tools for Visual Studio 2019, or install the .NET SDK.

. moniker range=»>=vs-2022″ If you have Visual Studio, then you already have MSBuild installed. With Visual Studio 2022, it’s installed under the Visual Studio installation folder. For a typical default installation on Windows 10, MSBuild.exe is under the installation folder in MSBuild\Current\Bin.

In the Visual Studio installer, navigate to Individual Components, and locate the checkbox for MSBuild. It is automatically selected when you choose any of the other workloads to install.

To install MSBuild on a system that doesn’t have Visual Studio, go to Build Tools for Visual Studio 2022 on the downloads page. Another way of getting MSBuild is to install the .NET SDK.

Create an MSBuild project

The Visual Studio project system is based on MSBuild. This makes it easy to create a new project file using Visual Studio. In this section, you create a Visual C# project file. You can choose to create a Visual Basic project file instead. In the context of this walkthrough, the difference between the two project files is minor.

To create a project file

Open Visual Studio and create a project:

In the search box, type winforms, then choose Create a new Windows Forms App (.NET Framework). In the dialog box that appears, choose Create.

In the Project name box, type BuildApp . Enter a Location for the solution, for example, D:\.

Click OK or Create to create the project file.

Examine the project file

In the previous section, you used Visual Studio to create a Visual C# project file. The project file is represented in Solution Explorer by the project node named BuildApp. You can use the Visual Studio code editor to examine the project file.

To examine the project file

In Solution Explorer, click the project node BuildApp.

In the Properties browser, notice that the Project File property is BuildApp.csproj. All project files are named with the suffix proj. If you had created a Visual Basic project, the project file name would be BuildApp.vbproj.

Right-click the project node again, then click Edit BuildApp.csproj.

The project file appears in the code editor.

[!NOTE] For some project types, such as C++, you need to unload the project (right-click on the project file and choose Unload project) before you can open and edit the project file.

Targets and tasks

Project files are XML-formatted files with the root node Project.

Most .NET projects have a Sdk attribute. These are called SDK-style projects.

There are many variations of .NET SDKs for special purposes; they are described at .NET Project SDKs.

The work of building an application is done with Target and Task elements.

A task is the smallest unit of work, in other words, the «atom» of a build. Tasks are independent executable components which may have inputs and outputs. There are no tasks currently referenced or defined in the project file. You add tasks to the project file in the sections below. For more information, see the Tasks topic.

A target is a named sequence of tasks. For more information, see the Targets topic.

[it might be a named sequence of tasks, but critically, it represents something to be built or done, so it should be defined in a goal-oriented way]

The default target is not defined in the project file. Instead, it is specified in imported projects. The Import element specifies imported projects. For example, in a C# project, the default target is imported from the file Microsoft.CSharp.targets.

Imported files are effectively inserted into the project file wherever they are referenced.

In SDK-style projects, you don’t see this import element, since the SDK attribute causes this file to be imported implicitly.

MSBuild keeps track of the targets of a build, and guarantees that each target is built no more than once.

Add a target and a task

Add a target to the project file. Add a task to the target that prints out a message.

To add a target and a task

Add these lines to the project file, just after the Import statement or the opening Project element.

This creates a target named HelloWorld. Notice that you have IntelliSense support while editing the project file.

Add lines to the HelloWorld target, so that the resulting section looks like this:

Save the project file.

The Message task is one of the many tasks that ships with MSBuild. For a complete list of available tasks and usage information, see Task reference.

The Message task takes the string value of the Text attribute as input and displays it on the output device (or writes it to one or more logs, if applicable). The HelloWorld target executes the Message task twice: first to display «Hello», and then to display «World».

Build the target

If you try to build this project from Visual Studio, it won’t build the target you defined. That’s because Visual Studio chooses the default target, which is still the one in the imported .targets file.

Run MSBuild from the Developer Command Prompt for Visual Studio to build the HelloWorld target defined above. Use the -target or -t command-line switch to select the target.

[!NOTE] We will refer to the Developer Command Prompt as the Command Window in the sections below.

To build the target:

Open the Command Window.

In the search box on the taskbar, start typing the name of the tool, such as dev or developer command prompt . This brings up a list of installed apps that match your search pattern.

If you need to find it manually, the file is LaunchDevCmd.bat in the <visualstudio installation folder>\Common7\Tools folder.

From the command window, navigate to the folder containing the project file, in this case, D:\BuildApp\BuildApp.

Run msbuild with the command switch -t:HelloWorld . This selects and builds the HelloWorld target:

Examine the output in the Command window. You should see the two lines «Hello» and «World»:

[!NOTE] If instead you see The target «HelloWorld» does not exist in the project then you probably forgot to save the project file in the code editor. Save the file and try again.

By alternating between the code editor and the command window, you can change the project file and quickly see the results.

Build properties are name-value pairs that guide the build. Several build properties are already defined at the top of the project file:

All properties are child elements of PropertyGroup elements. The name of the property is the name of the child element, and the value of the property is the text element of the child element. For example,

defines the property named TargetFrameworkVersion, giving it the string value «v4.5».

Build properties may be redefined at any time. If

appears later in the project file, or in a file imported later in the project file, then TargetFrameworkVersion takes the new value «v3.5».

Examine a property value

To get the value of a property, use the following syntax, where PropertyName is the name of the property:

Use this syntax to examine some of the properties in the project file.

To examine a property value

From the code editor, replace the HelloWorld target with this code:

Save the project file.

From the Command Window, enter and execute this line:

Examine the output. You should see these two lines (your output may differ):

Many properties like Configuration are defined conditionally, that is, the Condition attribute appears in the property element. Conditional properties are defined or redefined only if the condition evaluates to «true». Note that undefined properties are given the default value of an empty string. For example,

means «If the Configuration property has not been defined yet, define it and give it the value ‘Debug'».

Almost all MSBuild elements can have a Condition attribute. For more discussion about using the Condition attribute, see Conditions.

MSBuild reserves some property names to store information about the project file and the MSBuild binaries. MSBuildToolsPath is an example of a reserved property. Reserved properties are referenced with the $ notation like any other property. For more information, see How to: Reference the name or location of the project file and MSBuild reserved and well-known properties.

You can reference environment variables in project files the same way as build properties. For example, to use the PATH environment variable in your project file, use $(Path). If the project contains a property definition that has the same name as an environment variable, the property in the project overrides the value of the environment variable. For more information, see How to: Use environment variables in a build.

Set properties from the command line

Properties may be defined on the command line using the -property or -p command line switch. Property values received from the command line override property values set in the project file and environment variables.

To set a property value from the command line:

From the Command Window, enter and execute this line:

Examine the output. You should see this line:

MSBuild creates the Configuration property and gives it the value «Release».

Certain characters have special meaning in MSBuild project files. Examples of these characters include semicolons (;) and asterisks (*). In order to use these special characters as literals in a project file, they must be specified by using the syntax %<xx>, where <xx> represents the ASCII hexadecimal value of the character.

Change the Message task to show the value of the Configuration property with special characters to make it more readable.

To use special characters in the Message task:

From the code editor, replace both Message tasks with this line:

Save the project file.

From the Command Window, enter and execute this line:

Examine the output. You should see this line:

An item is a piece of information, typically a file name, that is used as an input to the build system. For example, a collection of items representing source files might be passed to a task named Compile to compile them into an assembly.

All items are child elements of ItemGroup elements. The item name is the name of the child element, and the item value is the value of the Include attribute of the child element. The values of items with the same name are collected into item types of that name. For example,

defines an item group containing two items. The item type Compile has two values: Program.cs and Properties\AssemblyInfo.cs.

The following code creates the same item type by declaring both files in one Include attribute, separated by a semicolon.

For more information, see Items.

[!NOTE] File paths are relative to the folder containing the MSBuild project file, even if the project file is an imported project file. There are a few exceptions to this, such as when using Import and UsingTask elements.

Examine item type values

To get the values of an item type, use the following syntax, where ItemType is the name of the item type:

Use this syntax to examine the Compile item type in the project file.

To examine item type values:

From the code editor, replace the HelloWorld target task with this code:

Save the project file.

From the Command Window, enter and execute this line:

Examine the output. You should see this long line:

The values of an item type are separated with semicolons by default.

To change the separator of an item type, use the following syntax, where ItemType is the item type and Separator is a string of one or more separating characters:

Change the Message task to use carriage returns and line feeds (%0A%0D) to display Compile items one per line.

To display item type values one per line

From the code editor, replace the Message task with this line:

Save the project file.

From the Command Window, enter and execute this line:

Examine the output. You should see these lines:

Include, Exclude, and wildcards

You can use the wildcards «*», «**», and «?» with the Include attribute to add items to an item type. For example,

adds all files with the file extension .jpeg in the images folder to the Photos item type, while

adds all files with the file extension .jpeg in the images folder, and all its subfolders, to the Photos item type. For more examples, see How to: Select the files to build.

Notice that as items are declared they are added to the item type. For example,

creates an item type named Photo containing all files in the images folder with a file extension of either .jpeg or .gif. This is equivalent to the following line:

You can exclude an item from an item type with the Exclude attribute. For example,

adds all files with the file extension .cs to the Compile item type, except for files whose names contain the string Designer. For more examples, see How to: Exclude files from the build.

The Exclude attribute only affects the items added by the Include attribute in the item element that contains them both. For example,

would not exclude the file Form1.cs, which was added in the preceding item element.

To include and exclude items

From the code editor, replace the Message task with this line:

Add this item group just after the Import element:

Save the project file.

From the Command Window, enter and execute this line:

Examine the output. You should see this line:

Items may contain metadata in addition to the information gathered from the Include and Exclude attributes. This metadata can be used by tasks that require more information about items than just the item value.

Item metadata is declared in the project file by creating an element with the name of the metadata as a child element of the item. An item can have zero or more metadata values. For example, the following CSFile item has Culture metadata with a value of «Fr»:

To get the metadata value of an item type, use the following syntax, where ItemType is the name of the item type and MetaDataName is the name of the metadata:

To examine item metadata:

From the code editor, replace the Message task with this line:

Save the project file.

From the Command Window, enter and execute this line:

Examine the output. You should see these lines:

Notice how the phrase «Compile.DependentUpon» appears several times. The use of metadata with this syntax within a target causes «batching». Batching means that the tasks within the target are executed once for each unique metadata value. This is the MSBuild script equivalent of the common «for loop» programming construct. For more information, see Batching.

Whenever an item is added to an item list, that item is assigned some well-known metadata. For example, %(Filename) returns the file name of any item. For a complete list of well-known metadata, see Well-known item metadata.

To examine well-known metadata:

From the code editor, replace the Message task with this line:

Save the project file.

From the Command Window, enter and execute this line:

Examine the output. You should see these lines:

By comparing the two examples above, you can see that while not every item in the Compile item type has DependentUpon metadata, all items have the well-known Filename metadata.

Item lists can be transformed into new item lists. To transform an item list, use the following syntax, where <ItemType> is the name of the item type and <MetadataName> is the name of the metadata:

For example, an item list of source files can be transformed into a collection of object files using an expression like @(SourceFiles -> ‘%(Filename).obj’) . For more information, see Transforms.

To transform items using metadata:

From the code editor, replace the Message task with this line:

Save the project file.

From the Command Window, enter and execute this line:

Examine the output. You should see this line:

Notice that metadata expressed in this syntax does not cause batching.

To learn how to create a simple project file one step at a time, on Windows, try out the Walkthrough: Creating an MSBuild project file from scratch.

If you’re primarily using the .NET SDK, you may wish to continue reading at MSBuild Reference for .NET SDK Projects.

Footer

© 2023 GitHub, Inc.

You can’t perform that action at this time.

You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *