删除 NuGet 源(如果存在)

Ada*_*uck 6 powershell nuget

我正在尝试检测源是否已添加到配置文件中。如果已添加,我想将其删除。棘手的部分是我最初不知道源的名称,但知道路径。

使用nuget sources list -configfile C:\Temp\NuGet.Config我能够识别已添加的源,但这会返回一个字符串。

如何根据源路径识别源是否已添加并提取源名称以便将其删除?

一些伪代码:

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
Run Code Online (Sandbox Code Playgroud)

dge*_*low 2

所以我有同样的问题,dotnet CLI 不支持基于源删除,这有点痛苦。

我是这样解决的:

$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
    }
}
Run Code Online (Sandbox Code Playgroud)

该脚本按行分割输出。然后,它检查该行是否与源名称行的格式匹配,在这种情况下,它会保存该名称。然后,如果遇到与提要 URL 匹配的行,它将删除具有先前保存的名称的源。

这依赖于dotnet nuget list source -format detailed,这是默认的,在我的例子中至少输出一个这样格式化的列表:

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\
Run Code Online (Sandbox Code Playgroud)

请注意,如果将来输出发生变化,或者您的 dotnet CLI 版本输出不同的内容,您可能需要调整正则表达式。