How to Install NuGet Packages (.nupkg) using PowerShell

NuGet packages (.nupkg files) contain reusable code libraries that can be incorporated into .NET projects to add functionality and save development time. Installing NuGet packages with PowerShell provides a fast, automated way to get libraries integrated.

In this comprehensive guide, you’ll learn:

  • What NuGet is and how it works
  • The benefits of using NuGet packages
  • How to find and download .nupkg files
  • How to install packages into projects using PowerShell
  • PowerShell commands for querying and managing packages
  • Tips for troubleshooting package installation issues

Follow along and you’ll be managing NuGet dependencies like a pro with PowerShell scripts in no time!

What is NuGet and How Does It Work?

NuGet is an open source package manager used for sharing and installing .NET libraries and frameworks. It serves as a central repository containing thousands of useful code packages to add capabilities to .NET apps.

The key advantages of NuGet include:

  • Dependency management – Automatically installs and references packages your projects require.
  • Version control – Supports different package versions and updating to newer releases.
  • Centralized repository – Public and private registries make finding and downloading packages easy.
  • Consistency – Standardizes project dependencies and configurations across teams.
  • PowerShell integration – Automates package management tasks using PowerShell cmdlets.

NuGet Packages

NuGet packages contain compiled code libraries bundled into .nupkg files. They may include:

  • .NET assemblies
  • Native DLLs
  • Resource files
  • Config files
  • Tools
  • Scripts
  • License docs

The .nupkg zipped folder structure contains the assemblies along with key metadata like version numbers, authors, descriptions, and dependencies in special manifest files.

Package Repositories

Public and private NuGet repositories host thousands of downloadable packages:

  • nuget.org – Public repository containing over 150,000 open source packages.
  • Private feeds – Organizations can host internal packages securely using NuGet server products like Azure Artifacts.

The NuGet CLI and client tools interact with repositories to search, download, and publish packages. PowerShell cmdlets work directly with the repositories as well.

Package Restore

NuGet can automatically download and install all the necessary package dependencies for a project during build time.

By sharing a simple packages.config or .csproj file that lists dependencies, NuGet will pull any missing packages from repositories and add references to projects before compiling code.

This powerful restore function keeps teams in sync and saves tons of manual package installation effort.

Now that you understand NuGet basics, let’s look at why using NuGet packages is so beneficial for .NET development.

Benefits of Using NuGet Packages

Here are some of the top reasons to manage .NET dependencies with NuGet:

Reduce Reinvention of Common Code

NuGet packages contain pre-built solutions for common tasks that you can reuse instantly instead of writing from scratch. Why code up logging, parsing, authentication etc. yourself when trusted implementations already exist?

Incorporate Robust Frameworks Quickly

Packages like Entity Framework, React.js, and Bootstrap add full robust frameworks and expansive functionality faster than building in-house.

Stay Updated with Latest Releases

As package authors update their code and release new versions, NuGet allows you to upgrade seamlessly. Never get stuck managing legacy package code yourself.

Discover New Libraries

Browsing NuGet repositories exposes you to great new specialty packages you may never have encountered otherwise for math, econometrics, analytics, and more.

Promote Open Source Sharing

Contributing your own useful packages back to the community promotes more collaboration and innovation in the .NET ecosystem.

Synchronize Team Dependencies

Using a shared packages.config allows all developers to pull same package versions, ensuring consistency and avoiding bugs from mismatches.

Automate tedium

NuGet handles all the tedious parts of obtaining, integrating, and upgrading packages automatically with just a few clicks.

Now that you see the many benefits NuGet packages provide, let’s move on to finding and downloading the ones you need.

Finding and Downloading NuGet Packages

With over 150,000 packages and growing, how do you find the perfect NuGet packages to use? Here are some strategies:

Browse nuget.org

The official public repository at nuget.org provides:

  • Search by keywords to find relevant packages
  • Filter by category like cloud, containers, databases etc.
  • Sort by popularity, relevance, published date etc.
  • See ratings, descriptions, version histories and more

Check Project Pages

Many open source .NET projects publish and recommend their own NuGet packages like:

  • ASP.NET Core
  • Entity Framework
  • ML.NET
  • Xamarin

Check their project pages for details on getting started with their packages.

Ask for Recommendations

Speaking to other .NET developers and asking for package suggestions on forums like StackOverflow can uncover great options.

Review Package Sources

Scan the source code of .NET libraries you like on Github and check their build scripts for NuGet dependencies you could leverage.

Once you’ve identified useful packages to install, acquiring them is straightfoward:

Download via nuget.org Web UI

  • Browse nuget.org and select a package
  • On the package page, find the latest version and click Download
  • Save the .nupkg file locally

nuget.exe CLI Tool

  • Open a command prompt
  • Run nuget install [PACKAGE_NAME]
  • The .nupkg file will be downloaded to local packages folder

Visual Studio UI

  • In Visual Studio, open the NuGet Package Manager
  • Browse to find your package and click Install
  • The IDE will handle downloading automatically

Now you have .nupkg package files ready to integrate into projects using PowerShell!

Installing NuGet Packages with PowerShell

PowerShell provides an automated way to install NuGet packages into projects with scripts instead of manual point-and-click.

Here are the key steps to add packages via PowerShell:

  1. Open PowerShell
  2. Navigate to project directory
  3. Install NuGet provider
  4. Import .nupkg file
  5. Call Install-Package on project

Let’s look at sample commands for each piece:

1. Launch PowerShell

Start a PowerShell session by running powershell.exe from the Start menu.

2. Navigate to Project

Change to your project’s directory that will receive the package.

cd C:\Projects\MyApp

3. Install NuGet Provider

The NuGet PS provider extends PowerShell with NuGet capabilities. Install it with:

Install-PackageProvider NuGet -Force

4. Import .nupkg File

Import the .nupkg file into the local NuGet repository:

Register-PackageSource -Name MyPackages -Location C:\packages -ProviderName NuGet

5. Install Package

Finally, install the package into the project:

Install-Package Newtonsoft.Json -Source MyPackages

This will add all required assemblies, imports, and references to integrate the Newtonsoft JSON package.

You can combine the steps into a single PowerShell script. Specify the exact package version if desired:

# Install NuGet Provider
Install-PackageProvider NuGet -Force 

# Import Package
Register-PackageSource -Name MyPackages -Location C:\packages -ProviderName NuGet  

# Install Package into Project
Install-Package Newtonsoft.Json -Version 12.0.1 -Source MyPackages

Executing this ensures the package gets imported and set up correctly every time with no manual intervention needed!

Alternative: Install from NuGet Repository

Instead of pre-downloading .nupkg files, you can install packages directly from an online NuGet repository like nuget.org:

# List available package sources  
Get-PackageSource

# Add nuget.org if missing
Register-PackageSource -Name nuget.org -Location https://www.nuget.org/api/v2 -ProviderName NuGet

# Install package from nuget.org
Install-Package Newtonsoft.Json -Source nuget.org

This queries the repository for the latest version and pulls it down on the fly.

PowerShell Commands for NuGet Packages

Beyond Install-Package, PowerShell provides tons of useful NuGet commands for managing packages:

  • Get-Package – Lists installed packages and versions
  • Find-Package – Searches repositories to find packages
  • Save-Package – Downloads packages to local storage
  • Uninstall-Package – Removes and unreferences packages
  • Update-Package – Updates packages to newer versions
  • Get-Project -All – Displays projects in the solution
  • Sync-Package – Synchronizes packages from one project to another

You can run these individually, but they really shine when combined into PowerShell scripts that automate your workflows:

Update All Packages

# List each project
Get-Project -All | ForEach-Object { 

    # Set current project
    Set-Location $_.FullName

    Write-Host Updating $($_.Name)

    # Update each installed package
    Get-Package -ProjectName $_.Name | ForEach-Object {
        Update-Package -ProjectName $_.ProjectName -Id $_.Id -Version $_.Version
    }
}

This loops through each project, lists its packages, and updates them to the latest versions automatically!

Move Package to Another Project

# Define source and destination projects
$sourceProj = "MyApp"
$destProj = "MyApp.Web"

# Get package to move
$package = Get-Package -ProjectName $sourceProj | Where-Object Id -eq "Newtonsoft.Json"

# Uninstall from source
Uninstall-Package -Id $package.Id -Version $package.Version -ProjectName $sourceProj

# Install into destination
Install-Package -Id $package.Id -Version $package.Version -ProjectName $destProj

Quickly migrates a package between projects with no hassle!

The package management automation possibilities are endless with PowerShell.

Troubleshooting Package Installation

Though NuGet installation through PowerShell is generally straightforward, you may encounter issues like:

  • Unexpected errors installing or updating packages
  • Assemblies not being referenced correctly
  • Old package versions remaining after update
  • Inconsistent behavior across environments

Here are some tips for troubleshooting:

  • Confirm the NuGet provider is installed properly in PowerShell
  • Check for typos in PowerShell package IDs or source names
  • Try reimporting the .nupkg file into local repository
  • Use verbose logging with -Verbose flag on commands
  • Identify differences in packages.config across environments
  • Restart Visual Studio and rebuild solution after PowerShell updates
  • Clear NuGet caches by deleting project packages folders
  • Reset repository sources and reinstall NuGet client tools
  • Search NuGet issues on GitHub in case its a known bug

With patience and care, you can resolve most erratic issues that arise with PowerShell NuGet integration. Don’t hesitate to reach out to package authors on forums if all else fails.

Putting It All Together

In summary, here is a step-by-step guide to install NuGet packages via PowerShell:

1) Find useful NuGet packages for your project needs

2) Download .nupkg files from nuget.org or other sources

3) Launch PowerShell and navigate to your project folder

4) Install the NuGet package provider if missing

5) Call Register-PackageSource to import packages into local repository

6) Use Install-Package to add packages to projects

7) Manage packages further with commands like Update-Package or Uninstall-Package

8) Build automation scripts to perform workflows like bulk upgrading

9) Debug issues by checking logs, clearing caches, and verifying configurations

Following these best practices will have you productively managing NuGet dependencies from PowerShell. Your projects will integrate the latest community code with minimal hassle.

NuGet packages allow standing on the shoulders of .NET giants who’ve solved common problems before. Automate integrating these powerful libraries using PowerShell, and you’ll transform how quickly your projects progress.

So try out a useful new package today using these techniques! With the vast NuGet ecosystem just a few keystrokes away, your next great project is closer than ever.

Leave a Comment