Brandon McClure
Brandon McClure

Reputation: 1400

Check if a nuget source is already configured

I want to add a nuget package feed that is hosted on our TFS instance to all of our developer's workstations. The problem that I have is that if the source has already been added, I get an error stating The name specified has already been added to the list of available package sources. Please provide a unique name.

What I want to do is check if a nuget source has already been registered on the machine before I run the code to add the source. Checking the documentation for nuget.exe I tried to use the List operation along with the Name and Source but I just get the same result as if I just run nuget sources

All of these commands:

nuget sources list -Source $myURL
nuget sources list -Name $myName
nuget sources

Return the same result:

Registered Sources:

  1.  nuget.org [Enabled]
      https://api.nuget.org/v3/index.json
  2.  myPowershellFeed [Enabled]
    https://myURL.myDomain.org

I am using Powershell to run these commands and came up with a workaround, but ideally I am hoping there is a nuget.exe command line option that will get this info for me.

Upvotes: 20

Views: 21986

Answers (3)

Grengas
Grengas

Reputation: 1054

This is a simple Windows cmd line to add a new nuget source if it hasn't been added before (in this case source name is "test"):

nuget sources | findstr test || (nuget sources Add -Name test -Source "https://some-nuget-source")

So what it does, it tries to find string "test" in listed nuget sources, if it finds it, it does nothing, otherwise it proceeds with adding a new source.

Upvotes: 8

Maximilian Burszley
Maximilian Burszley

Reputation: 19684

In PowerShell v5, you have access to the PackageManagement module. This includes a NuGet package provider:

$nuget = Get-PackageProvider -Name NuGet

Alongside this, you can access all your sources:

$nuget | Get-PackageSource

By default, this will only have nuget.org, but with your added source(s), you will see them from the result of this command as well. As a bonus, because it's a powershell command, it returns objects instead of strings, so you can do the following:

Get-PackageSource -Name myPowershellFeed |
    Format-List -Property * -Force

To address your Q&A:

if (-not $(Get-PackageSource -Name myPowershellFeed -ProviderName NuGet -ErrorAction Ignore))
{
    # add the packagesource

Upvotes: 16

Matheus Valiente Souza
Matheus Valiente Souza

Reputation: 368

You can use the follow line:

$nugetHasMyUrlSource =!!(nuget source | ? { $_ -like "*$myUrl"})

Or even encapsulate it in a function:

function HasNugetSource ($url){
    return !!(nuget source | ? { $_ -like "*$url"});
}

Upvotes: 4

Related Questions