Using PowerShell to Publish a NuGet Package
Join the DZone community and get the full member experience.
Join For FreeAt my employer we have a local NuGet server to host all of our internal packages. Occasionally, I’ll be working on a project and realize that I need to tweak something in one of my NuGet packages. Initially, I got into the habit of opening up a second instance of Visual Studio, making the necessary changes and using the NuGet web interface to re-upload the package. I quickly realized that manually uploading the package was too time consuming. Therefore, I started looking for a way to automate the process instead. Eventually that led me to the PowerShell script you see below.
$nugetServer = "https://<your nuget server here>" $apiKey = "<your api key here>" $packageName = "<your package name here>" $latestRelease = nuget list $packageName $version = $latestRelease.split(" ")[1]; $versionTokens = $version.split(".") $buildNumber = [System.Double]::Parse($versionTokens[$versionTokens.Count -1]) $versionTokens[$versionTokens.Count -1] = $buildNumber +1 $newVersion = [string]::join('.', $versionTokens) echo $newVersion get-childitem | where {$_.extension -eq ".nupkg"} | foreach ($_) {remove-item $_.fullname} nuget pack -Version $newVersion $package = get-childitem | where {$_.extension -eq ".nupkg"} nuget push -Source $nugetServer $package $apiKey
The script needs a few variables defined in order for it to run.
The first variable ($nugetServer) is the URL of the NuGet Server. The
second variable ($apiKey) is your personal API key. You can get your API
key by logging into your NuGet Server with a browser. After you log in,
click on your username in the upper right hand corner. This will take
you to your account page. On the bottom of the “My Account” page there
is a box which you can click on to make your API key visible. Finally
the last variable ($packageName) is the name of the package you are
uploading. This can be easily acquired by looking at your project
properties and copying the Assembly name from the Application tab.
Depending on how your machine is configured you may have the option to Run with PowerShell on your context menu. If not, you can take a look at this blog post in order to configure it manually. Alternatively you can use the following command instead.
powershell.exe "<path to the script>\publish.ps1"
If you have any problems running the script then please refer to the following TechNet article or send me a question and I’ll be glad to help.
Opinions expressed by DZone contributors are their own.
Comments