Skip to content

Instantly share code, notes, and snippets.

@celloza
Last active May 4, 2022 08:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save celloza/889edb3c7276952635bf0bb9068693a8 to your computer and use it in GitHub Desktop.
Save celloza/889edb3c7276952635bf0bb9068693a8 to your computer and use it in GitHub Desktop.
param (
[Parameter(Mandatory=$true)]
[string]$feedName,
[Parameter(Mandatory=$true)]
[string]$url
)
$profilePath = [System.Environment]::GetFolderPath([System.Environment+SpecialFolder]::UserProfile)
$pluginLocation = [System.IO.Path]::Combine($profilePath, ".nuget", "plugins");
$localNetfxCredProviderPath = [System.IO.Path]::Combine("netfx", "CredentialProvider.Microsoft");
$fullNetfxCredProviderPath = [System.IO.Path]::Combine($pluginLocation, $localNetfxCredProviderPath)
$netfxExists = Test-Path -Path ($fullNetfxCredProviderPath)
if($netfxExists -eq $false)
{
Write-Host "Installing credential provider..."
iex "& { $(irm https://aka.ms/install-artifacts-credprovider.ps1) } -AddNetfx"
$netfxExists = Test-Path -Path ($fullNetfxCredProviderPath)
if($netfxExists -eq $false)
{
Write-Host "Credentials provider is required."
Write-Host "Maybe install manually from https://github.com/microsoft/artifacts-credprovider/releases"
return
}
}
else
{
Write-Host "Credential Provider already exists."
}
$exe = [System.IO.Path]::Combine($fullNetfxCredProviderPath, 'CredentialProvider.Microsoft.exe')
# It's not possible to disable device based authentication, but we can set timeout to fail immidiately.
$ENV:NUGET_CREDENTIALPROVIDER_VSTS_DEVICEFLOWTIMEOUTSECONDS=0
# Validity period: 1 year. (Can have larger value)
$ENV:NUGET_CREDENTIALPROVIDER_VSTS_SESSIONTIMEMINUTES=365*24*60
# '-V Error' is required not to get extra messages
$msg = & $exe -V Error -U $url -C -F JSON 2>&1 | Out-String
if($lastexitcode -ne 0)
{
Write-Host "$msg"
Write-Host "Failed to run '$exe' ($lastexitcode)"
return
}
try
{
$info = ConvertFrom-Json $msg
}
catch
{
Write-Host "$msg"
return
}
Write-Host "Your PAT is $info.Password. Make a copy of it, as it will not be accessible again. It will also be added to the list of credentials that NuGet uses."
$nugetConfig = [System.Environment]::ExpandEnvironmentVariables("%APPDATA%\NuGet\nuget.config")
$nuget = 'nuget.exe'
$msg = & $nuget sources remove -name $feedName -config $nugetConfig 2>&1 | Out-String
& $nuget sources add -name $feedName -source $url -username MyOwnPat -password $info.Password -StorePasswordInClearText -config $nugetConfig 2>&1 | Out-Null
Write-Output $info.Password
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment