Powershell script to re-install Nuget packages


Here's a simple Powershell script I wrote to re-install the Nuget packages that are associated with the current Visual Studio solution.

In case you're wondering why you might want to do this, I often create backups of code that I'm working on.  I deliberately exclude the "packages" folder from the backup so I keep the backup file size as small as possible.  For what it's worth, I typically exclude the "bin" and "obj" folders too.  Anyway, if I need to refer to one of my backups, I wanted a way to easily re-build the packages folder.  As the packages.config file IS included in my backups, I can easily re-install the relevant packages via the following Powershell script executed from the Nuget Package Manager Console.  For example:

PM> .\Install-Packages.ps1

Where "Install-Packages.ps1" contains the following code and is in the same folder as my Visual Studio solution (.sln) file:

 

$projects = Get-Project -All

foreach($proj in $projects)
{
 $projName = $proj.Name
 Write-Host "Processing project $projName..."

 $path = Join-Path (Split-Path $proj.FileName) packages.config

 if(Test-Path $path)
 {
  Write-Host "Processing $path..."

  $xml = $packages = Get-Content $path
  foreach($package in $packages.packages.package)
  {
   $id = $package.id
   Write-Host "Installing package $id..."      
       Install-Package -Id $id -Version $package.version
  }
 }
}

 

A possible improvement would be to wrap the above code in a Powershell function and include that unction in my Nuget profile as discussed in Setting up a NuGet Powershell Profile.

Comments (0)

Skip to main content