register a repository conditionally in powershell

Viewed 184

I want to register a powershell repository in the following manner:

if((Get-PSRepository -Name $artifactory.Key.ToString().Trim()) -eq $null)
{
        #register the repository if not found
        $Location = "$($ConfigInfo.ArtifactoryCredentials.ArtifactoryServer.ToString().Trim())/$($artifactory.Value.ToString().Trim())"

        Write-Host "Registering repositories $($Location)" -ForegroundColor Cyan

        Register-PSRepository -Name $artifactory.Key.ToString().Trim() -SourceLocation $Location `
                                                                       -PublishLocation $Location `
                                                                       -InstallationPolicy Trusted -Verbose
}

It seems that the condition checking is not valid because the code steps into the if block with the following error:

PackageManagement\Get-PackageSource : Unable to find repository

Getting into the if block is valid, but it enter with an error, which I would like to suppress

How do I check if repo is found or not ?

1 Answers

Just negate the condition using ! Operator and add erroraction to ignore:

if(!(Get-PSRepository -Name $artifactory.Key.ToString().Trim() -ErrorAction Ignore ))
Related