Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get MSBuild to restore any needed NuGet packages

I've looked at a ton of articles on this including here and here. None provide a solution that I can get to work.

I have everything turned on for automatically doing this in VisualStudio. But on our build machine we build the .sln files using MSBuild, not by opening up VisualStudio. So in MSBuild how can I best do this?

All of our .sln files are for VisualStudio 2019 and set to defaults on handling NuGet (I believe).

like image 493
David Thielen Avatar asked Sep 12 '25 06:09

David Thielen


2 Answers

msbuild -t:Restore will restore nuget packages for projects with PackageReference nuget management format.

And your situation looks like packages.config nuget management format which you have used it.

If so, you only should use nuget restore to restore nuget packages with msbuild.exe.

1) first download nuget.exe cli from the website and config it. You can check this about it.

2) then use MSBuild command line, type

nuget xxx\xxx.sln restore
msbuild xxx\xxx.sln -t:build

Another is to use msbuild -t:restore with -p:RestorePackagesConfig=true.

msbuild xxx\xxx.sln -t:build -restore -p:RestorePackagesConfig=true
like image 103
Mr Qian Avatar answered Sep 15 '25 00:09

Mr Qian


I think this might have worked for me, to include it in every build without extra cli. (but I had the problem only sporadically)

Edit your project file to include a new target just before the closing </project> tag:

  <Target Name="EnsureNugetRestoreBeforeResolveRefs"
          DependsOnTargets="Restore" 
          BeforeTargets="BeforeResolveReferences"/>

Or, if you need the RestorePackagesConfig parameter:

  <Target Name="EnsureNugetRestoreBeforeResolveRefs" BeforeTargets="BeforeResolveReferences">
    <PropertyGroup>
      <RestorePackagesConfig>true</RestorePackagesConfig>
    </PropertyGroup>
    <Message Condition="'$(RestorePackagesConfig)' == 'True'" Text="RestorePackagesConfig=true" />
    <CallTarget Targets="Restore"/>
  </Target>

like image 45
Chris F Carroll Avatar answered Sep 14 '25 22:09

Chris F Carroll