25

I have a .NET Core 1.1 console project created with Visual Studio 2017. After building the project, I need to run a powershell script so I added the following to the MyProject.csproj file:

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

Now I need to build the project in a Linux environment, I need to instruct MSBuild to run execute-tasks.sh instead of execute-tasks.ps1 when it is running in Linux.

I believe this is achievable via the Condition attribute, but is there an MSBuild variable that holds the operating system name?

3 Answers 3

35

The variable is $(OS), usually checked against being or not being Windows_NT:

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

Using $(OS), as documented in other answers, can distinguish between Windows_NT and Unix (which includes both Linux and macOS), but not between different Unix-like systems. If you are using MSBuild 15.3 or later (which is very likely), you may want to consider using [MSBuild]::IsOsPlatform():

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

The argument can be the name of any OsPlatform member.

3
  • 1
    Nice, that worked for me (using Windows instead of Linux). Jun 29, 2021 at 22:46
  • 1
    There's even $([MSBuild]::IsOSUnixLike()) as a shortcut to the above 😉
    – Oliver
    Jan 17 at 23:12
  • This doesn't work in a docker container May 19 at 8:27
0

You can use the target something like this. Seems OS version is not an environment variable in MSBUILD.

 <Target Name="AfterBuild">
          <Exec Command="foo.exe arg1 arg2" Condition=" '$(OS)' == 'Windows_NT' " />
 </Target>

or another example, this may be cumbersome.

<?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>
2
  • 2
    Just that registry access isn't that helpful on *nix systems. even if run on windows, it only works when using the full framework msbuild, not the .net core version that ships with the CLI. Apr 19, 2017 at 15:21
  • Ok I wasnt aware of the of .net core version. Apr 19, 2017 at 15:23

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.