【问题标题】:How to get the current operating system in MSBuild?如何在 MSBuild 中获取当前操作系统?
【发布时间】:2017-09-15 21:20:40
【问题描述】:

我有一个使用 Visual Studio 2017 创建的 .NET Core 1.1 控制台项目。 构建项目后,我需要运行一个 powershell 脚本,因此我将以下内容添加到 MyProject.csproj 文件中:

<Target Name="PostcompileScript" AfterTargets="Build">
    <Exec Command="execute-tasks.ps1" />
</Target>

现在我需要在 Linux 环境中构建项目,我需要指示 MSBuild 在 Linux 中运行时运行 execute-tasks.sh 而不是 execute-tasks.ps1。

我相信这可以通过Condition 属性实现,但是是否有一个保存操作系统名称的 MSBuild 变量?

【问题讨论】:

    标签: linux bash msbuild .net-core visual-studio-2017


    【解决方案1】:

    变量为$(OS),通常检查是否为Windows_NT:

    <Exec Command="./foo.sh" Condition=" '$(OS)' != 'Windows_NT' " />
    

    【讨论】:

    • 操作系统指令的官方文档在哪里?还有哪些其他操作系统选项?
    • 这里有一个关于可以在官方 MSBuild 存储库中返回的值的问题讨论 - github.com/Microsoft/msbuild/issues/539 - 我没有研究最终结果是什么,但显然可能的值是 Windows_NT、Unix也许还有 OSX(Github 中的问题)。
    【解决方案2】:

    您可以像这样使用目标。似乎操作系统版本不是 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>
    

    【讨论】:

    • 只是注册表访问对 *nix 系统没有太大帮助。即使在 Windows 上运行,它也仅在使用完整框架 msbuild 时有效,而不是 CLI 附带的 .net 核心版本。
    • 好吧,我不知道 .net 核心版本。
    【解决方案3】:

    使用$(OS),如其他答案中所述,可以区分Windows_NT 和Unix(包括Linux 和macOS),但不能区分不同的类Unix 系统。如果您使用的是 MSBuild 15.3 或更高版本(很有可能),您可能需要考虑使用[MSBuild]::IsOsPlatform():

    <Exec Command="./foo.sh" Condition="$([MSBuild]::IsOSPlatform('Linux'))" />
    

    参数可以是任何OsPlatform 成员的名称。

    【讨论】:

    • 很好,这对我有用(使用 Windows 而不是 Linux)。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-02-01
    • 1970-01-01
    • 2010-11-06
    • 1970-01-01
    • 2018-03-14
    • 2011-03-05
    • 2010-12-06
    相关资源
    最近更新 更多