Restoring nuget packages on build servers or without Visual Studio

Nuget’s package restore is automated by the visual studio extension but what about when msbuild.exe runs against the .sln?¬†When you execute the build without the packages you will end up with errors:

warning MSB3245: Could not resolve this reference. Could not locate the assembly

Fortunately we can create a file called ‘after.<SolutionName>.sln.targets’ replacing <SolutionName> with your soltion and putting it in in the folder with the solution and Nuget.exe.

Put the follow contents:

<?xml version=”1.0″ encoding=”utf-8″?>
<Project ToolsVersion=”14.0″ xmlns=”″>
<Target Name=”RestoreNuget” BeforeTargets=”Build”>
<Exec Command=”&quot;Nuget.exe&quot; restore &quot;$(SolutionPath)&quot;” WorkingDirectory=”$(MSBuildProjectDirectory)”/>

Now when you run msbuild.exe ExampleApplication.sln

“Nuget.exe” restore “C:\Dev\Repos\Blog\2015-11 – Solution Package Restore\ExampleApplication.sln”
Installing ‘Microsoft.Web.Xdt 2.1.1’.
Successfully installed ‘Microsoft.Web.Xdt 2.1.1’.
Installing ‘NuGet.Core 2.9.0’.
Successfully installed ‘NuGet.Core 2.9.0’.

You can also do things like Upgrade with the -safe flag for continuous integration situations. You can see the example of this on GitHub: