Pack and deploy NuGet packages with PowerShell

Posted in category powershell on 2014-09-23
Tags: nuget, powershell

Table of Contents

Prerequisites

NuGet specification for project(s)

In order to make project visible to NuGet packager it is necessary to have *.nuspec file created side by side with *.csproj file. File names should be aligned as well, such that if project file name is Logging.csproj then NuGet specification file should be named Logging.nuspec.

Let’s assume that Logging project is dependent on another project in the solution called Core as well as on third party library, NLog. NuGet specification for such project will look like following:

<?xml version="1.0"?>
<package xmlns="http://schemas.microsoft.com/packaging/2010/07/nuspec.xsd">
  <metadata>
    <id>$id$</id>
    <version>$version$</version>
    <authors>$author$</authors>
    <requireLicenseAcceptance>false</requireLicenseAcceptance>
    <description>$description$</description>
    <tags>logging nlog</tags>
    <language>en-US</language>
    <dependencies>
      <dependency id="Core" version="$version$" />
      <dependency id="NLog" version="3.1.0.0" />
    </dependencies>
  </metadata>
</package>

Important things to note here are placeholder variables like \(id\), \(version\), \(author\), etc. Values for these placeholders will be extracted from assembly information for Logging project by NuGet during packaging process in runtime.

Such NuGet specification files should be produced for each and every project in your solution that you would like to pack and deploy to NuGet repository.

You could find more detailed information on Nuspec Reference.

Packing and Deploying NuGet Packages

The gist of NuGet packing process is very simple:

In order to submit single package to a repository the following command can be issued:

NuGet pack "Logging.csproj" `
  -Properties "Configuration=Release" `
  -o "C:/Path/To/Local/Repository"

In order to submit all the configured NuGet packages to a repository some scripting might be handy. The following powershell script executed from the folder holding solution file, should pack and deploy all the NuGet packages in your solution:

# Define some parameters
$TargetPath = "C:/Path/To/Local/Repository"
$BuildConfiguration = "Release"

# Find all the *.nuspec files and deliberately omit NuGet packages
$specs = @(Get-ChildItem "./" -Filter "*.nuspec" -Recurse | `
  ? { $PSItem.FullName -inotmatch "\\packages\\" } | `
  % { $PSItem.FullName } `
)

# Find relevant *.csproj files
foreach ($spec in $specs) {
  $folder = $(Split-Path $spec -Parent)
  $prjs = @(Get-ChildItem $folder -Filter "*.csproj" | % { $PSItem.FullName } )
  if ($prjs.Count -gt 0) {
    $prj = @($prjs)[0]
    NuGet pack "$prj" `
      -Properties "Configuration=$BuildConfiguration" `
      -o "$TargetPath"
  }
}