The most direct method to set WinHTTP proxy settings on a Windows machine is to edit its registry. The hive is located at “HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Internet Settings\Connections” and the reg_binary key name is “WinHttpSettings.” The trick is to convert from default PowerShell characters to binary values so that such key can be updated using PowerShell. Here’s the snippet to accomplish that task:

# Dynamic variables
$proxy = "http://proxy:8080"
$exclusionList="localhost;*.kimconnect.com"

# Set proxy registry
$asciiValue = "(   $proxy $exclusionList" #The hidden binary characters wouldn't show up as ASCII chars so this conversion doesn't work, currently
$winHTTPHive = "Registry::HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Internet Settings\Connections";
$winHTTPKey = "WinHttpSettings";
$binaryValue = [system.Text.Encoding]::Default.GetBytes($asciiValue) | %{[System.Convert]::ToString($_) }
Set-ItemProperty -Path $winHTTPHive -Name $winHTTPKey -Value $binaryValue
# Check values
$WinHttpValue=(Get-ItemProperty -Path $winHTTPHive -Name $winHTTPKey).WinHttpSettings

# Display Binary as Unicode
[Text.Encoding]::Unicode.getString($WinHttpValue)
[System.Text.Encoding]::Unicode.GetString($WinHttpValue)

# Display Binary as ASCCI - PowerShell default
[Text.Encoding]::ASCII.getString($WinHttpValue)

Expected result:

PS C:\Windows> [Text.Encoding]::ASCII.getString($WinHttpValue)
(   http://proxy:8080 localhost;*.kimconnect.com

This is the result of a Windows machine’s WinHTTPSettings value for NO PROXY

Windows Group Policy: Setting WinHTTP Proxy

Registry Hive: HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Internet Settings\Connections
Key Name: WinHttpSettings
Value (for Direct Access or No Proxy): 1800000000000000010000000000000000000000

Error when Authentication is required:

PS C:\Users\kimconnect> Invoke-WebRequest 
Invoke-WebRequest : Proxy Authorization Required
Description: Authorization is required for access to this proxy
At line:1 char:1
+ Invoke-WebRequest
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (System.Net.HttpWebRequest:HttpWebRequest) [Invoke-WebRequest], WebException
+ FullyQualifiedErrorId : WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeWebRequestCommand

Possible Fixes:

# Method 0: Use the time-tested legacy command netsh to set winhttp proxy - this seems to work well and render other methods unnecessary
$proxy="http://proxy:8080"
$exclusionList="localhost;*.kimconnect.com"
netsh winhttp set proxy $proxy

# Check Result
PS C:\Users\kdoan-a> netsh winhttp show proxy

Current WinHTTP proxy settings:

Proxy Server(s) : http://proxy:8080
Bypass List : localhost;*.kimconnect.com
# Method 1: Set PowerShell User Agent to be recognized by the proxy and authenticate via Default AD credential
$webClient = new-object System.Net.WebClient
$webClient.Headers.Add(“user-agent”, “PowerShell Script”)
$webClient.Proxy.Credentials = [System.Net.CredentialCache]::DefaultNetworkCredentials

# Method 2: Run 1-off Web Request commands
$Proxy = "http://proxy:80"
$Password = ConvertTo-SecureString "PASSWORD" -AsPlainText -Force
$Credentials = New-Object System.Management.Automation.PSCredential -ArgumentList "DOMAIN\ADMINISTRATOR",$Password
Invoke-WebRequest -uri https://www.google.com/ -Proxy $Proxy -ProxyCredential $Credentials

# Method 3: NO Basic Auth. copy proxy address from http proxy to winhttp
$proxy = [System.Net.WebProxy]::GetDefaultProxy().Address
[system.net.webrequest]::defaultwebproxy = New-Object system.net.webproxy($proxy)
[system.net.webrequest]::defaultwebproxy.credentials = [System.Net.CredentialCache]::DefaultNetworkCredentials
[system.net.webrequest]::defaultwebproxy.BypassProxyOnLocal = $true

# Method 4: [YES] Basic Auth. copy proxy address from http proxy to winhttp
$proxy = [System.Net.WebProxy]::GetDefaultProxy().Address
[system.net.webrequest]::defaultwebproxy = New-Object system.net.webproxy($proxy)
$credCache = [System.Net.CredentialCache]::new()
$credentials = [System.Net.NetworkCredential]::new("USERNAME","PASSWORD","KIMCONNECT")
$credCache.Add($proxy, "Basic", $credentials)

Some Results:

PS C:\Users\kimconnect> Test-NetConnection -Computername google.com -Port 80 -InformationLevel Quiet
WARNING: TCP connect to google.com:80 failed
False
PS C:\Users\kimconnect> Invoke-WebRequest -uri https://www.google.com/
Invoke-WebRequest : The underlying connection was closed: An unexpected error occurred on a send.
At line:1 char:1
+ Invoke-WebRequest -uri https://www.google.com/
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (System.Net.HttpWebRequest:HttpWebRequest) [Invoke-WebRequest], WebException
+ FullyQualifiedErrorId : WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeWebRequestCommand
PS C:\Users\kimconnect> iwr google.com


StatusCode : 200
StatusDescription : OK
Content : <!doctype html><html itemscope="" itemtype="http://schema.org/WebPage" lang="en"><head><meta content="Search the world's information,
including webpages, images, videos and more. Google has many speci...
RawContent : HTTP/1.1 200 OK
X-XSS-Protection: 0
X-Frame-Options: SAMEORIGIN
Cache-Control: private, max-age=0
Content-Type: text/html; charset=UTF-8
Date: Tue, 30 Apr 2019 23:26:35 GMT
Expires: -1
P3P: CP=...
Forms : {f}
Headers : {[X-XSS-Protection, 0], [X-Frame-Options, SAMEORIGIN], [Cache-Control, private, max-age=0], [Content-Type, text/html; charset=UTF-8]...}
Images : {@{innerHTML=; innerText=; outerHTML=<IMG id=hplogo onload=window.lol&amp;&amp;lol() style="PADDING-BOTTOM: 14px; PADDING-TOP: 28px;
PADDING-LEFT: 0px; PADDING-RIGHT: 0px" alt=Google src="/images/branding/googlelogo/1x/googlelogo_white_background_color_272x92dp.png"
width=272 height=92>; outerText=; tagName=IMG; id=hplogo; onload=window.lol&amp;&amp;lol(); style=PADDING-BOTTOM: 14px; PADDING-TOP: 28px;
PADDING-LEFT: 0px; PADDING-RIGHT: 0px; alt=Google; src=/images/branding/googlelogo/1x/googlelogo_white_background_color_272x92dp.png;
width=272; height=92}}
InputFields : {@{innerHTML=; innerText=; outerHTML=<INPUT type=hidden value=en name=hl>; outerText=; tagName=INPUT; type=hidden; value=en; name=hl},
@{innerHTML=; innerText=; outerHTML=<INPUT type=hidden value=hp name=source>; outerText=; tagName=INPUT; type=hidden; value=hp;
name=source}, @{innerHTML=; innerText=; outerHTML=<INPUT type=hidden name=biw>; outerText=; tagName=INPUT; type=hidden; name=biw},
@{innerHTML=; innerText=; outerHTML=<INPUT type=hidden name=bih>; outerText=; tagName=INPUT; type=hidden; name=bih}...}
Links : {@{innerHTML=<SPAN class=gbtb2></SPAN><SPAN class=gbts>Search</SPAN>; innerText=Search; outerHTML=<A onclick=gbar.logger.il(1,{t:1});
id=gb_1 class="gbzt gbz0l gbp1" href="https://www.google.com/webhp?tab=ww"><SPAN class=gbtb2></SPAN><SPAN class=gbts>Search</SPAN></A>;
outerText=Search; tagName=A; onclick=gbar.logger.il(1,{t:1});; id=gb_1; class=gbzt gbz0l gbp1; href=https://www.google.com/webhp?tab=ww},
@{innerHTML=<SPAN class=gbtb2></SPAN><SPAN class=gbts>Images</SPAN>; innerText=Images; outerHTML=<A onclick=gbar.logger.il(1,{t:2});
id=gb_2 class=gbzt href="http://www.google.com/imghp?hl=en&amp;tab=wi"><SPAN class=gbtb2></SPAN><SPAN class=gbts>Images</SPAN></A>;
outerText=Images; tagName=A; onclick=gbar.logger.il(1,{t:2});; id=gb_2; class=gbzt; href=http://www.google.com/imghp?hl=en&amp;tab=wi},
@{innerHTML=<SPAN class=gbtb2></SPAN><SPAN class=gbts>Maps</SPAN>; innerText=Maps; outerHTML=<A onclick=gbar.logger.il(1,{t:8}); id=gb_8
class=gbzt href="http://maps.google.com/maps?hl=en&amp;tab=wl"><SPAN class=gbtb2></SPAN><SPAN class=gbts>Maps</SPAN></A>; outerText=Maps;
tagName=A; onclick=gbar.logger.il(1,{t:8});; id=gb_8; class=gbzt; href=http://maps.google.com/maps?hl=en&amp;tab=wl}, @{innerHTML=<SPAN
class=gbtb2></SPAN><SPAN class=gbts>Play</SPAN>; innerText=Play; outerHTML=<A onclick=gbar.logger.il(1,{t:78}); id=gb_78 class=gbzt
href="https://play.google.com/?hl=en&amp;tab=w8"><SPAN class=gbtb2></SPAN><SPAN class=gbts>Play</SPAN></A>; outerText=Play; tagName=A;
onclick=gbar.logger.il(1,{t:78});; id=gb_78; class=gbzt; href=https://play.google.com/?hl=en&amp;tab=w8}...}
ParsedHtml : System.__ComObject
RawContentLength : 45920
PS C:\Users\kimconnect> iwr download.microsoft.com
iwr : The underlying connection was closed: An unexpected error occurred on a send.
At line:1 char:1
+ iwr download.microsoft.com
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (System.Net.HttpWebRequest:HttpWebRequest) [Invoke-WebRequest], WebException
+ FullyQualifiedErrorId : WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeWebRequestCommand

Errors when Basic Credentials and Network Logins are required:

PS C:\Users\kimconnect> Get-WUInstall –MicrosoftUpdate –AcceptAll –AutoReboot
WARNING: Exception from HRESULT: 0x80072EE2. Probably you don't have connection to Windows Update server.
PS C:\WINDOWS> Start-BitsTransfer -Source $url -Destination $output -Asynchronous
Start-BitsTransfer : The operation being requested was not performed because the user has not logged on to the
network. The specified service does not exist. (Exception from HRESULT: 0x800704DD)
At line:1 char:1
+ Start-BitsTransfer -Source $url -Destination $output -Asynchronous
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [Start-BitsTransfer], COMException
+ FullyQualifiedErrorId : System.Runtime.InteropServices.COMException,Microsoft.BackgroundIntelligentTransfer.Mana
gement.NewBitsTransferCommand
PS C:\WINDOWS> Invoke-WebRequest -Uri $url -OutFile $output
Invoke-WebRequest : The underlying connection was closed: An unexpected error occurred on a send.
At line:1 char:1
+ Invoke-WebRequest -Uri $url -OutFile $output
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (System.Net.HttpWebRequest:HttpWebRequest) [Invoke-WebRequest], WebExc
eption
+ FullyQualifiedErrorId : WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeWebRequestCommand
PS C:\WINDOWS> (New-Object System.Net.WebClient).DownloadFile($url, $output)
Exception calling "DownloadFile" with "2" argument(s): "The underlying connection was closed: An unexpected error
occurred on a send."
At line:1 char:1
+ (New-Object System.Net.WebClient).DownloadFile($url, $output)
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : WebException

Windows Update URLs to Whitelist:


http://*.windowsupdate.microsoft.com
https://*.windowsupdate.microsoft.com
http://*.update.microsoft.com
https://*.update.microsoft.com
http://*.windowsupdate.com
http://download.windowsupdate.com

http://*.download.windowsupdate.com

https://support.microsoft.com/en-us/windows/windows-update-faq-8a903416-6f45-0718-f5c7-375e92dddeb2