Windows OS Hub
  • Windows Server
    • Windows Server 2022
    • Windows Server 2019
    • Windows Server 2016
    • Windows Server 2012 R2
    • Windows Server 2008 R2
    • SCCM
  • Active Directory
    • Active Directory Domain Services (AD DS)
    • Group Policies
  • Windows Clients
    • Windows 11
    • Windows 10
    • Windows 8
    • Windows 7
    • Windows XP
    • MS Office
    • Outlook
  • Virtualization
    • VMWare
    • Hyper-V
    • KVM
  • PowerShell
  • Exchange
  • Cloud
    • Azure
    • Microsoft 365
    • Office 365
  • Linux
    • CentOS
    • RHEL
    • Ubuntu
  • Home
  • About

Windows OS Hub

  • Windows Server
    • Windows Server 2022
    • Windows Server 2019
    • Windows Server 2016
    • Windows Server 2012 R2
    • Windows Server 2008 R2
    • SCCM
  • Active Directory
    • Active Directory Domain Services (AD DS)
    • Group Policies
  • Windows Clients
    • Windows 11
    • Windows 10
    • Windows 8
    • Windows 7
    • Windows XP
    • MS Office
    • Outlook
  • Virtualization
    • VMWare
    • Hyper-V
    • KVM
  • PowerShell
  • Exchange
  • Cloud
    • Azure
    • Microsoft 365
    • Office 365
  • Linux
    • CentOS
    • RHEL
    • Ubuntu

 Windows OS Hub / PowerShell / Using PowerShell Behind a Proxy Server

May 10, 2023 PowerShellWindows 10Windows 11Windows Server 2019Windows Server 2022

Using PowerShell Behind a Proxy Server

If your computer is on a corporate network behind a proxy server, by default you won’t be able to access external web resources from your PowerShell CLI. For example, you won’t be able to get the content of an external web page using the Invoke-WebRequest cmdlet, update help using the Update-Help, connect to Azure/Microsoft 365 tenant (Exchange Online PowerShell module), install modules from PSGallery, or RSAT capabilities, download an application package from an external package repository (using WinGet package manager). In this article, we’ll show you how to configure PowerShell to access the Web through a proxy server with authentication.

Let’s try to update the PowerShell Help on a computer behind a corporate proxy server:

Update-Help

Or refer to an external web page:

Invoke-WebRequest https://woshub.com
If your computer can only access the Web through a proxy and not through a direct connection, the command will return an error:

Update-help : Failed to update Help for the module(s) ‘DhcpServer, DirectAccessClientComponents….’  with UI culture(s) {en-US} : Unable to connect to Help content. The server on which Help content is stored might not be available. Verify that the server is available, or wait until the server is back online, and then try the command again.
Invoke-WebRequest: Unable to connect to the remote server.
InvalidOperation: (System.Net.HttpWebRequest:HttpWebRequest).

Find-Module modulename

Unable to resolve package source 'https://www.powershellgallery.com/api/v2'

can't connect to the Internet from PowerShell over the authenticated proxy server

The fact is that Powershell (or rather, the .NET class System.Net.WebClient, which these cmdlets used to access external resources over HTTP/HTTPS) does not use the proxy server settings specified in the user settings. Let’s take a look at how to configure proxy server settings and perform authentication from the PowerShell console.

Contents:
  • Set WinHTTP Proxy Server Settings for PowerShell
  • Proxy Authentication with PowerShell
  • Configuring Proxy Connections for PowerShell Core
  • Apply Proxy Server Settings with PowerShell Profile File
  • Show Current Proxy Server Settings with PowerShell
  • How to Change Proxy Settings in Windows with PowerShell?

Set WinHTTP Proxy Server Settings for PowerShell

Check the current system proxy setting from PowerShell:

netsh winhttp show proxy

As you can see, proxy settings are not specified:

Current WinHTTP proxy settings:
Direct access (no proxy server).

netsh winhttp show proxy

You can import proxy server configurations from Windows settings (Internet Explorer):

netsh winhttp import proxy source=ie

or set them manually:

netsh winhttp set proxy "192.168.0.14:3128"

netsh winhttp set proxy

You can specify a list of IP addresses or site names that you don’t need to use a proxy server to connect to (bypass list):

netsh winhttp set proxy "192.168.1.100:3128" bypass-list= "10.*,172.*,192.168.*,*.corp.woshub.com"

You can centrally configure Winnhttp proxy settings on domain computers using a GPO.

You can check if the connection to a specific URL is through a proxy or not: ([System.Net.WebRequest]::GetSystemWebproxy()).IsBypassed("https://woshub.com")

powershell: check proxy connection

If the command returns False, the connection to this URL will be made through the proxy configured in your PowerShell session.

If the proxy server requires authentication, an error like “(407) Proxy Authentication Required” will appear when you try to run PowerShell commands. For example, when trying to connect to your Azure tenant using the AzureAD module:

Connect-AzureAD

An error occurs:

The remote server returned an error: (407) Proxy Authentication Required.

Next, let’s look at how to authenticate to a proxy server from PowerShell.

Proxy Authentication with PowerShell

Let’s look at two ways to authenticate to a proxy server: you can use Windows SSO authentication or specify user credentials for authentication manually.

If you are authorized on your computer under a domain account, and your proxy server supports Active Directory Kerberos, or NTLM authentication (if you have not disabled it yet), then you can use the current user credentials to authenticate on the proxy server (you do not need to re-enter your username and password):

$Wcl = new-object System.Net.WebClient
$Wcl.Headers.Add(“user-agent”, “PowerShell Script”)
$Wcl.Proxy.Credentials = [System.Net.CredentialCache]::DefaultNetworkCredentials

If you need to manually authenticate on the proxy server manually, run the following commands and specify the username and password in the Windows Security credential request window.

$Wcl=New-Object System.Net.WebClient
$Creds=Get-Credential
$Wcl.Proxy.Credentials=$Creds

powershell: get credentials to authenticate on a proxy server

Now you can try to access an external website or update the help with the Update-Help command.

Using PowerShell from behind authenticated proxy

Or, if you have configured a proxy connection in a PowerShell session, the command should return the external IP address of your proxy server:

(Invoke-WebRequest -uri "http://ifconfig.me/ip").Content

As you can see, the Invoke-Web Request cmdlet returned data from the external site webpage!

If you don’t want to use the proxy settings for the entire PowerShell session, you can use the special parameters of the Invoke-WebRequest cmdlet to authenticate to the proxy as the current user:

Invoke-WebRequest https://woshub.com -ProxyUseDefaultCredentials -Proxy http://192.168.1.100:3128

Or you can request user credentials interactively:

$ProxyCreds = Get-Credential
Invoke-WebRequest https://woshub.com -Proxy "http://192.168.1.100:3128" -ProxyCredential $ProxyCreds

The above method allows you to configure proxy server settings and authenticate in classic Windows PowerShell 5.1 (How to check the PowerShell version installed?).

Configuring Proxy Connections for PowerShell Core

In new versions of PowerShell Core (6.x, 7.x), the System.Net.HttpClient class is used instead of the System.Net.WebRequest class to perform web requests in the Invoke-WebRequest, Find-Module, Install-Module, etc. cmdlets.

Accordingly, to set proxy server settings in PowerShell Core, you need to use the command:

[System.Net.Http.HttpClient]::DefaultProxy = New-Object System.Net.WebProxy('http://your-proxy:3128')

To authenticate on the proxy under the current Windows user:

[System.Net.Http.HttpClient]::DefaultProxy.Credentials = [System.Net.CredentialCache]::DefaultCredentials

To interactively request user credentials for proxy authentication:

[System.Net.Http.HttpClient]::DefaultProxy.Credentials = Get-Credential

PowerShell Core also supports special Windows environment variables you can use to enable proxy settings:

  • HTTP_PROXY – proxy for HTTP requests
  • HTTPS_PROXY — proxy for HTTPS requests
  • ALL_PROXY – proxy for both HTTP and HTTPS
  • NO_PROXY – proxy exclusion address list

You can set environment variables with the following PowerShell commands:

$proxy='http://192.168.1.100:8080'
$ENV:HTTP_PROXY=$proxy
$ENV:HTTPS_PROXY=$proxy

You can save the username and password for authentication on the proxy server in the environment variables (not secure):

$proxy='http://username:password@IP:PORT'

Check that the proxy environment variables are set:

Dir env:

powershell core set http proxy

In PowerShell Core on Linux, you can export system proxy settings from environment variables using:

export HTTP_PROXY=http://192.168.1.100:3128
export HTTPS_PROXY=http://192.168.1.100:3128

Apply Proxy Server Settings with PowerShell Profile File

You can create a PowerShell profile file to automatically import proxy settings when PowerShell starts.

To do this, run the command that will create the PowerShell profile file (C:\Users\username\Documents\WindowsPowerShell\Microsoft.PowerShell_profile.ps1):

notepad $PROFILE (or notepad $PROFILE.AllUsersCurrentHost –if you need to apply a PowerShell profile to all users of the computer).

A PowerShell profile is a simple PS script that always runs when you open the PowerShell.exe console.

Copy your PowerShell code into the notepad window. For example, you are using the Proxy Auto-Configuration (PAC) files to automatically configure proxy server settings on user computers. You can specify the URL address of the PAC file and authenticate on the proxy server under the current user with the following PowerShell profile script.

# Force PowerShell to use TLS 1.2 for connections
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
[system.net.webrequest]::DefaultWebProxy = new-object system.net.webproxy('http://10.1.15.5:80')
# If you need to import proxy settings from Internet Explorer, you can replace the previous line with the: "netsh winhttp import proxy source=ie"
[system.net.webrequest]::DefaultWebProxy.credentials = [System.Net.CredentialCache]::DefaultNetworkCredentials
# You can request user credentials:
# System.Net.WebRequest]::DefaultWebProxy.Credentials = Get-Credential
# Also, you can get the user password from a saved XML file (see the article “Using saved credentials in PowerShell scripts”):
# System.Net.WebRequest]::DefaultWebProxy= Import-Clixml -Path C:\PS\user_creds.xml
[system.net.webrequest]::DefaultWebProxy.BypassProxyOnLocal = $true

By default, the PowerShell Script Execution Policy doesn’t allow PS scripts to run, even from PowerShell profile files. To allow PS1 scripts to run, you need to change your PowerShell Execution Policy settings. Run the command:

Set-ExecutionPolicy RemoteSigned

Save the Microsoft.PowerShell_profile.ps1 file and restart the PowerShell console. Now, when you open a new PowerShell session, the code in the profile file is executed and the proxy settings are imported into your session.

Show Current Proxy Server Settings with PowerShell

You can get the current proxy settings in Windows from the registry with the PowerShell command:

Get-ItemProperty -Path 'HKCU:\Software\Microsoft\Windows\CurrentVersion\Internet Settings' | Select-Object ProxyServer, ProxyEnable

In my example, the address and port of the proxy server are: 192.168.1.100:3128
Proxy server enabled: ProxyEnable =1

powershell get proxy settings

You can also get WebProxy settings like this:

[System.Net.WebProxy]::GetDefaultProxy()

System.Net.WebProxy GetDefaultProxy powershell

If necessary, you can enable the use of proxy with the following command:

Set-ItemProperty -Path 'HKCU:\Software\Microsoft\Windows\CurrentVersion\Internet Settings' ProxyEnable -value 1

To disable proxy:
Set-ItemProperty -Path 'HKCU:\Software\Microsoft\Windows\CurrentVersion\Internet Settings' ProxyEnable -value 0

How to Change Proxy Settings in Windows with PowerShell?

You can set proxy settings using PowerShell. For example, the following PowerShell function allows you to change proxy settings, but first, it checks the availability of the proxy server and the port response on it using the Test-NetConnection cmdlet

function Set-Proxy ( $server,$port)
{
If ((Test-NetConnection -ComputerName $server -Port $port).TcpTestSucceeded) {
Set-ItemProperty -Path 'HKCU:\Software\Microsoft\Windows\CurrentVersion\Internet Settings' -name ProxyServer -Value "$($server):$($port)"
Set-ItemProperty -Path 'HKCU:\Software\Microsoft\Windows\CurrentVersion\Internet Settings' -name ProxyEnable -Value 1
}
Else {
Write-Error -Message "Invalid proxy server address or port:  $($server):$($port)"
}
}

Set-Proxy 192.168.1.100 3128

You can add additional addresses to the proxy exclusion list:

$ProxyExceptionList = ";*.woshub.com;*.contoso.com"
$ProxyProperty = Get-ItemProperty "HKCU:\Software\Microsoft\Windows\CurrentVersion\Internet Settings"
If ($ProxyProperty.ProxyOverride) {
$OldValue = $ProxyProperty.ProxyOverride
$NewValue = $OldValue+$ProxyExceptionList
$ProxyProperty | Set-ItemProperty -Name ProxyOverride -Value $NewValue
} else {
Write-Warning "List of proxy overrides is empty!"
}

Additionally, you can save the login and password  for authentication on the proxy server in the registry:

Set-ItemProperty -Path 'HKCU:\Software\Microsoft\Windows\CurrentVersion\Internet Settings' -name ProxyUser -Value "proxy_username"
Set-ItemProperty -Path 'HKCU:\Software\Microsoft\Windows\CurrentVersion\Internet Settings' -name ProxyPass -Value "proxy_password"

Note that older builds of Windows 10, Windows Server 2016, and older versions of Windows use the outdated and insecure TLS 1.0 protocol by default for PowerShell connections. This is why you may get the following error when trying to search for a module in PSGallery:

WARNING: Unable to resolve package source 'https://www.powershellgallery.com/api/v2'.

To use TLS 1.2 in PowerShell connections to endpoints, run the command

[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12

The problem is described in more detail in the article “Unable to resolve package source when installing PowerShell modules”.

15 comments
9
Facebook Twitter Google + Pinterest
previous post
How to Access VMFS Datastore from Linux, Windows, or ESXi
next post
Recovering a Deleted VMFS Datastore on VMware ESXi/vSphere

Related Reading

Zabbix: How to Get Data from PowerShell Scripts

October 27, 2023

Tracking Printer Usage with Windows Event Viewer Logs

October 19, 2023

PowerShell: Configure Certificate-Based Authentication for Exchange Online (Azure)

October 15, 2023

How to Query and Change Teams User Presence...

October 8, 2023

How to Use Ansible to Manage Windows Machines

September 25, 2023

15 comments

David McKinnon February 13, 2018 - 6:58 pm

My Company uses Autoconfig proxy PAC files on the workstations and a static proxy on servers – I located the following Powershell entries that worked for me on my Windows 10 client running PS5.1:

The x.x.x.x below is the IP Address and port of the PAC server:

[system.net.webrequest]::defaultwebproxy = new-object system.net.webproxy(‘http://x.x.x.x:80’)
[system.net.webrequest]::defaultwebproxy.credentials = [System.Net.CredentialCache]::DefaultNetworkCredentials
[system.net.webrequest]::defaultwebproxy.BypassProxyOnLocal = $true

Command:

Invoke-WebRequest https://woshub.com|select RawContent

Output:

RawContent
———-
HTTP/1.1 200 OK…

I spent several weeks trying different options – I hope this can help someone out there in la la land… Dave

Reply
Amardeep May 17, 2018 - 10:31 am

For my company’s environment, David’s solution worked for me finally!
Just one thing to add…if you need to pass the NT Credentials :
[System.Net.WebRequest]::DefaultWebProxy.Credentials = Get-Credential

Reply
Petr Sors October 17, 2018 - 2:47 pm

Great article, cheers.

Reply
crispin owuor November 20, 2018 - 5:46 pm

this article was a lifesaver!!!!! was able to configure our company proxy to perform a deployment agent setup. the issue is i got an error. Exception calling “DownloadFile” with “2” argument(s): “The remote server returned an error: (407) Proxy
Authentication Required.”
At line:1 char:1269
+ … nalString, $True);}; $WebClient.DownloadFile($Uri, $agentZip);Add-Typ …
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], ParentContainsErrorRecordException
+ FullyQualifiedErrorId : WebException

Reply
Mark Rainbird February 11, 2019 - 5:10 pm

I ahve spent hours trying to get my scripts to run and your article has sorted it out for me – thanks so much!

Reply
James MA June 28, 2019 - 8:36 am

I can run “Invoke-WebRequest _https://woshub.com”, the proxy setting is OK.
But still fail to install package such as
> Install-PackageProvider -Name NuGet -MinimumVersion 2.8.5.201 -Force

It seems this setting only work for http protocol, but not for https.

Do you know how to set the proxy for https? Thanks a lot.

Reply
admin July 8, 2019 - 4:48 am

Try the following PowerShell code to access HTTPS website via proxy:
$Creds=Get-Credential
$proxy = New-Object System.Net.WebProxy
$proxy.Address = [uri]”http://yourproxy:3128″
$proxy.Credentials = $Creds
[System.Net.WebRequest]::DefaultWebProxy = $proxy
Invoke-WebRequest -Uri “https://contoso.com”

Reply
XB March 14, 2022 - 8:49 pm

WARNING: Unable to download from URI
WARNING: Unable to download the list of available providers. Check your internet connection.
PackageManagement\Install-PackageProvider : No match was found for the specified search criteria for the provider ‘NuGet’. The package provider requires ‘PackageManagement’ and ‘Provider’ tags. Please check if the specified package has the tags.

It turns out that this is a TLS issue, PowerShell does not use TLS 1.2 by default, while Microsoft requires TLS 1.2 from clients. To set TLS 1.2 usage for PowerShell, you can use the following command:
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
https://woshub.com/powershell-install-module-unable-download-uri/

Reply
Mohammed March 4, 2020 - 4:38 am

When you need to set authenticated proxy

$WebProxy = New-Object System.Net.WebProxy(“http://proxyname:proxyport”,$true)
$url=”https://woshub.com”
$WebClient = New-Object net.webclient
$password=”xxxxx”
$WebClient.proxy.Credentials = New-Object System.Net.NetworkCredential(“Username”,$password)

Reply
Matthew Erb October 29, 2020 - 12:09 pm

Thanks for the help, I had a tough time figuring this one out!

This is what worked for me:

$Wcl = new-object System.Net.WebClient
$Wcl.Headers.Add(“user-agent”, “PowerShell Script”)
$Wcl.Proxy.Credentials = [System.Net.CredentialCache]::DefaultNetworkCredentials

Reply
ME February 16, 2021 - 10:40 am

It did not work for me.
If i enable/disable the internet explorer Proxy Settings – the registry settings get overwritten.

When i set the proxy via netsh winhttp again the proxy settings in the registry does not get set.
Only via Internet Explorer – Server 2019

Reply
Tony Jeffries October 1, 2021 - 12:30 pm

Hello,

First, thank you for this article!
I have been trying to get NT AUTHORITY\SYSTEM to use a proxy and this is the only way that I have found to make it work.
My implementation is serving a different purpose in that I need the proxy to be active for more than just a PS Session.
I used a startup script to set the settings.

Set-ItemProperty -Path ‘HKCU:\Software\Microsoft\Windows\CurrentVersion\Internet Settings’ -name ProxyEnable -value 1
Set-ItemProperty -Path ‘HKCU:\Software\Microsoft\Windows\CurrentVersion\Internet Settings’ -name ProxyServer -value “myexampleproxy.com:8080”

My problem is that I need it to use AD Auth and local IP bypass.
I don’t see a way to set AD Auth except creating an instance of System.Net.WebProxy, but that won’t apply outside of Powershell.

My current workaround for this is just allowing unauthenticated traffic on the proxy for the t resources needed.
I have no workaround for the IP Bypass list.

Is there any way you can help?

Things that I have tried:
1. Binary WinHTTP settings in the registry
2. Copying settings from IE via CLI (only affects current user)

Reply
Windows proxy settings ultimate guide part II – configuring proxy settings – IP loging July 15, 2022 - 11:58 am

[…] For some more info please check this link […]

Reply
MP November 11, 2022 - 11:48 am

I set the proxy successfully but still can not ping!
running ping -t google.com returns:
Ping request could not find host google.com. Please check the name and try again

Reply
admin November 16, 2022 - 8:33 am

ping doesn’t work through proxy.

Reply

Leave a Comment Cancel Reply

Categories

  • Active Directory
  • Group Policies
  • Exchange Server
  • Microsoft 365
  • Azure
  • Windows 11
  • Windows 10
  • Windows Server 2022
  • Windows Server 2019
  • Windows Server 2016
  • PowerShell
  • VMWare
  • Hyper-V
  • Linux
  • MS Office

Recent Posts

  • Zabbix: How to Get Data from PowerShell Scripts

    October 27, 2023
  • Tracking Printer Usage with Windows Event Viewer Logs

    October 19, 2023
  • PowerShell: Configure Certificate-Based Authentication for Exchange Online (Azure)

    October 15, 2023
  • Reset Root Password in VMware ESXi

    October 12, 2023
  • How to Query and Change Teams User Presence Status with PowerShell

    October 8, 2023
  • How to Increase Size of Disk Partition in Ubuntu

    October 5, 2023
  • How to Use Ansible to Manage Windows Machines

    September 25, 2023
  • Installing Language Pack in Windows 10/11 with PowerShell

    September 15, 2023
  • Configure Email Forwarding for Mailbox on Exchange Server/Microsoft 365

    September 14, 2023
  • How to View and Change BIOS (UEFI) Settings with PowerShell

    September 13, 2023

Follow us

  • Facebook
  • Twitter
  • Telegram
Popular Posts
  • Fix: Remote Desktop Licensing Mode is not Configured
  • Manage Windows Updates with PSWindowsUpdate PowerShell Module
  • Configuring Port Forwarding in Windows
  • Start Menu or Taskbar Search Not Working in Windows 10/11
  • How to Install Remote Server Administration Tools (RSAT) on Windows
  • How to Delete Old User Profiles in Windows
  • Get-ADUser: Find Active Directory User Info with PowerShell
Footer Logo

@2014 - 2023 - Windows OS Hub. All about operating systems for sysadmins


Back To Top