If you do a lot of PowerShell work, you may find yourself frequently using NuGet or PsGallery. I’ve put a couple functions together that quickly add the PsGallery repository and NuGet respectively, and add trust to these sources. These functions were built to be modular so they could be modified for other sources as well. Do not run this if you don’t trust these sources. Here is the code:
Function Add-TrustedRepo {
param (
[string]$name
)
do {
$repos= $(Get-PsRepository).Name
if ($repos -notcontains $name) {
Write-Host "$name repository is not currently registered."
Write-Host "Registering $name repository now."
Register-PSRepository -Default -InstallationPolicy Trusted | Out-Null
} else {
$installationPolicy = $(Get-PsRepository | Where-Object {$_.Name -eq $name}).InstallationPolicy
if ($installationPolicy -eq 'Untrusted') {
Write-Host "$name repository is currently installed."
Write-Host "$name repository is not currently trusted."
Write-Host "Setting $name to trusted repository."
Set-PSRepository -Name $name -InstallationPolicy Trusted
}
Write-Host "$name repository is currently installed."
Write-Host "$name repository is currently trusted."
}
$i++
} until ($repos -contains $name -or $i -eq 2)
}
# install if needed/trust PSGallery as trusted
Add-TrustedRepo -Name "PSGallery"
Function Add-NuGet {
$package = Get-PackageSource -Name 'Nuget' -ErrorAction SilentlyContinue
if ($package.IsTrusted -eq $False) {
Write-Host "NuGet is installed, but is not trusted."
Write-Host "Setting NuGet as trusted source."
Set-PackageSource -Name 'Nuget' -Trusted -Force
} elseif ($package -eq $null) {
Write-Host "NuGet is not currently a registered source."
Write-Host "Registering NuGet as trusted source."
Register-PackageSource -Name Nuget -Location "https://www.nuget.org/api/v2" –ProviderName Nuget -Trusted -Force
} else {
Write-Host "NuGet is currently registered as a trusted source."
}
}
Add-NuGet