如何在 MSBuild 中获取当前操作系统?
How to get the current operating system in MSBuild?
我有一个使用 Visual Studio 2017 创建的 .NET Core 1.1 控制台项目。
构建项目后,我需要 运行 一个 powershell 脚本,所以我将以下内容添加到 MyProject.csproj
文件中:
<Target Name="PostcompileScript" AfterTargets="Build">
<Exec Command="execute-tasks.ps1" />
</Target>
现在我需要在 Linux 环境中构建项目,我需要在 [=26] 时指示 MSBuild 运行 execute-tasks.sh
而不是 execute-tasks.ps1
=]宁 Linux.
我相信这可以通过 Condition
属性实现,但是 是否有保存操作系统名称的 MSBuild 变量?
变量是$(OS)
,通常检查是不是Windows_NT
:
<Exec Command="./foo.sh" Condition=" '$(OS)' != 'Windows_NT' " />
您可以像这样使用目标。似乎 OS version 不是 MSBUILD 中的环境变量。
<Target Name="AfterBuild">
<Exec Command="foo.exe arg1 arg2" Condition=" '$(OS)' == 'Windows_NT' " />
</Target>
或者另一个例子,这可能很麻烦。
<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="OSVersion" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<OsVersion>$(registry:HKEY_LOCAL_MACHINE\Software\Microsoft\Windows NT\CurrentVersion@CurrentVersion).$(registry:HKEY_LOCAL_MACHINE\Software\Microsoft\Windows NT\CurrentVersion@CurrentBuildNumber)</OsVersion>
</PropertyGroup>
<Target Name="OSVersion">
<Message Text="Version: $(OsVersion)" />
</Target>
</Project>
使用$(OS)
,如其他答案中所述,可以区分Windows_NT
和Unix
(包括Linux和macOS),但不能区分不同的Unix -样的系统。如果您使用的是 MSBuild 15.3 或更高版本(很有可能),您可能需要考虑使用 [MSBuild]::IsOsPlatform()
:
<Exec Command="./foo.sh" Condition="$([MSBuild]::IsOSPlatform('Linux'))" />
参数可以是任何 OsPlatform
成员的名称。
我有一个使用 Visual Studio 2017 创建的 .NET Core 1.1 控制台项目。
构建项目后,我需要 运行 一个 powershell 脚本,所以我将以下内容添加到 MyProject.csproj
文件中:
<Target Name="PostcompileScript" AfterTargets="Build">
<Exec Command="execute-tasks.ps1" />
</Target>
现在我需要在 Linux 环境中构建项目,我需要在 [=26] 时指示 MSBuild 运行 execute-tasks.sh
而不是 execute-tasks.ps1
=]宁 Linux.
我相信这可以通过 Condition
属性实现,但是 是否有保存操作系统名称的 MSBuild 变量?
变量是$(OS)
,通常检查是不是Windows_NT
:
<Exec Command="./foo.sh" Condition=" '$(OS)' != 'Windows_NT' " />
您可以像这样使用目标。似乎 OS version 不是 MSBUILD 中的环境变量。
<Target Name="AfterBuild">
<Exec Command="foo.exe arg1 arg2" Condition=" '$(OS)' == 'Windows_NT' " />
</Target>
或者另一个例子,这可能很麻烦。
<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="OSVersion" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<OsVersion>$(registry:HKEY_LOCAL_MACHINE\Software\Microsoft\Windows NT\CurrentVersion@CurrentVersion).$(registry:HKEY_LOCAL_MACHINE\Software\Microsoft\Windows NT\CurrentVersion@CurrentBuildNumber)</OsVersion>
</PropertyGroup>
<Target Name="OSVersion">
<Message Text="Version: $(OsVersion)" />
</Target>
</Project>
使用$(OS)
,如其他答案中所述,可以区分Windows_NT
和Unix
(包括Linux和macOS),但不能区分不同的Unix -样的系统。如果您使用的是 MSBuild 15.3 或更高版本(很有可能),您可能需要考虑使用 [MSBuild]::IsOsPlatform()
:
<Exec Command="./foo.sh" Condition="$([MSBuild]::IsOSPlatform('Linux'))" />
参数可以是任何 OsPlatform
成员的名称。