Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove NuGet source if exists

I am trying to detect whether or not a source has been added to a configuration file. If it has been added, I would like to remove it. The tricky part is that I won't know the name of the source initially but am aware of the path.

Using nuget sources list -configfile C:\Temp\NuGet.Config I am able to identify the sources that have been added but this returns a string.

How can I identify if the source has been added based on the source path and extract the name of the source so that I can remove it?

Some pseudo code:

nuget sources add -name "example.com" -source "https://nuget.example.com/nuget" -username "example" -password "example" -storepasswordincleartext -configfile C:\Temp\NuGet.Config

if source exists with path 'https://nuget.example.com/nuget':
    remove source
like image 243
Adam Chubbuck Avatar asked May 29 '26 20:05

Adam Chubbuck


1 Answers

So I had the same question, it's a bit of a pain the dotnet CLI doesn't support removing based on a source.

I solved it this way:

$feedUrl = "<YourFeedUrl>"
$sources = dotnet nuget list source
$sourceName = ""
$sources -split "`n" | %{
    if($_ -match '^\s+\d+\.\s+(.*)\s+\[Enabled\]$'){
        $sourceName = $matches[1]
    } elseif ($_ -match "^\s+$feedUrl$") {
        dotnet nuget remove source $sourceName
    }
}

This script splits the output by lines. It then checks if the line matches the format of a source name line, in which case it saves the name. Then if it encounters a line matching the feed URL, it removes the source with the previously saved name.

That relies on dotnet nuget list source -format detailed, which is the default, and in my case at least outputs a list formatted this way:

Registered Sources:
  1.  nuget.org [Enabled]
      https://api.nuget.org/v3/index.json
  2.  Microsoft Visual Studio Offline Packages [Enabled]
      C:\Program Files (x86)\Microsoft SDKs\NuGetPackages\

Note that if the output changes in the future, or if your version of the dotnet CLI outputs something different, you may need to tweak the regex.

like image 66
dgellow Avatar answered Jun 01 '26 15:06

dgellow



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!