I have to admit – executing the same command three times and expecting different results is dumb, but I still do it anyway. Fortunately, after trying three times I usually resort to other methods and try to solve the problem I have. Today while trying to trust PowerShellGallery I was greeted with an error.
Microsoft.PowerShell.Management\Test-Connection : Invalid class
At C:\Program Files\WindowsPowerShell\Modules\PowerShellGet\1.0.0.1\PSModule.psm1:6094 char:22
+ … connected = Microsoft.PowerShell.Management\Test-Connection -Computer …
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [Test-Connection], ManagementException
+ FullyQualifiedErrorId : TestConnectionException,Microsoft.PowerShell.Commands.TestConnectionCommand
The error is cryptic – Invalid Class for a Test-Connection during Set-PSRepository trusted installation policy. That's not good, and not really an error that is obvious. Fortunately, I read the whole error and noticed one little thing. The error was coming from PowerShellGet 1.0.0.1 version. One thing to know about PowerShellGet is that it comes bundled in on newer systems or when you install PowerShell 5.1. And just like Pester it's heavily outdated at the start.
Instead of trying to analyze the error, go thru code and see where it's failing the first instinct that kicks in is to just update that PowerShell Module. So what you do is to run 2 little commands:
PS C:\Windows\system32> Set-PSRepository -name PSGallery -InstallationPolicy Trusted Microsoft.PowerShell.Management\Test-Connection : Invalid class At C:\Program Files\WindowsPowerShell\Modules\PowerShellGet\1.0.0.1\PSModule.psm1:6094 char:22 + ... connected = Microsoft.PowerShell.Management\Test-Connection -Computer ... + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : InvalidOperation: (:) [Test-Connection], ManagementException + FullyQualifiedErrorId : TestConnectionException,Microsoft.PowerShell.Commands.TestConnect PS C:\Windows\system32> install-module PowershellGet -Force PS C:\Windows\system32> import-module powershellget -force PS C:\Windows\system32> Set-PSRepository -name PSGallery -InstallationPolicy Trusted PS C:\Windows\system32>
And as I thought, it worked! You may wonder why I was using Install-Module instead of Update-Module. This is because you can't update module that wasn't installed from PowerShellGallery.
get-module -ListAvailable PowerShellGet
As you can see now, we have two versions of PowerShellGet, but we use only the newest one.