MSBuild /t:pack Nuget-Package has always the same Version

The MSBuild-integrated Pack target reads its value from MSBuild properties inside the project (PackageVersion to be specific, which is defaulted from Version, which in turn is defaulted to VersionPrefix which in turn may be suffixed by VersionSuffix).

There is out-of-the-box support for reading this value from an assembly attribute since the new project format is meant to generate these assembly attributes from the same configuration that determines NuGet package metadata.

However, you can extend the build by adding a custom target to the csproj file that reads the built assembly's identity during msbuild /t:Pack:

<Project>

  <PropertyGroup>
    <TargetFramework>netstandard2.0</TargetFramework>
    <GenerateAssemblyInfo>false</GenerateAssemblyInfo>
    <GenerateNuspecDependsOn>$(GenerateNuspecDependsOn);ReadPackageVersionFromOutputAssembly</GenerateNuspecDependsOn>
  </PropertyGroup>

  <Target Name="ReadPackageVersionFromOutputAssembly" DependsOnTargets="Build">
    <GetAssemblyIdentity AssemblyFiles="$(TargetPath)">
      <Output TaskParameter="Assemblies" ItemName="PackAssembly" />
    </GetAssemblyIdentity>
    <PropertyGroup>
      <PackageVersion>%(PackAssembly.Version)</PackageVersion>
    </PropertyGroup>
  </Target>

</Project>

Note that this target will only run on the "full MSBuild", that is msbuild.exe on windows (visual studio developer command prompt) or mono 5.2+ on linux/Mac. This currently does not work for dotnet pack (.NET Core version of MSBuild). UPDATE: This will now work in .NET SDKs 2.1.* and higher since the GetAssemblyIdentity task has been added to the cross-platform version of msbuild in 2018.


With current version of MSBuild it is possible to specify PackageVersion parameter:

msbuild ProjectName.csproj -t:Pack -p:PackageVersion=1.2.3