In Windows PowerShell, I use the following code in my profile to force all cmdlets to use my proxy (like Update-Help, etc.):
using namespace System.Net
using namespace System.Security.Principal
$isAdmin = ([WindowsPrincipal][WindowsIdentity]::GetCurrent()).IsInRole([WindowsBuiltInRole]::Administrator)
if ($isAdmin)
{
[WebRequest]::DefaultWebProxy = [WebProxy]::new('http://proxy:port')
[WebRequest]::DefaultWebProxy.Credentials = [CredentialCache]::DefaultNetworkCredentials
}
$wc = [WebClient]::new()
$wc.Proxy.Credentials = [CredentialCache]::DefaultNetworkCredentials
I have additional code to handle certificates / SSL:
@([Enum]::GetValues([SecurityProtocolType])).
Where{$PSItem -gt [Math]::Max(
[ServicePointManager]::SecurityProtocol.value__,
[SecurityProtocolType]::Tls.value__
)}.
ForEach{[ServicePointManager]::SecurityProtocol = [ServicePointManager]::SecurityProtocol -bor $PSItem}
[ServicePointManager]::ServerCertificateValidationCallback = {$true}
This works, however, the msdn documentation recommends moving to System.Net.Http.HttpClient instead, so I've tried implementing these same ideas there:
using namespace System.Net
using namespace System.Security.Authentication
Add-Type -AssemblyName System.Net.Http, System.Net.Http.WebRequest
$handler = [System.Net.Http.WebRequestHandler]::new()
$handler.UseDefaultCredentials = $true
$handler.DefaultProxyCredentials = [CredentialCache]::DefaultNetworkCredentials
$handler.SslProtocols = [SslProtocols]::Tls12
$handler.ServerCertificateValidationCallback = {$true}
$http = [System.Net.Http.HttpClient]::new($handler, $true)
Connections with this code fail saying I'm not passing my proxy credentials. I'm wondering what the difference in the interactions here is so I can further my understanding.