Windows OS Hub
  • Windows Server
    • Windows Server 2022
    • Windows Server 2019
    • Windows Server 2016
    • Windows Server 2012 R2
    • Windows Server 2012
    • 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 2012
    • 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

January 29, 2020 PowerShell

Using PowerShell Behind a Proxy Server

If you can access the Internet from your computer only via a proxy server, then by default you won’t be able to access external web resources from your PowerShell session: a webpage (Invoke-WebRequest cmdlet), update help using the Update-Help cmdlet, connect to Office365/Azure, or download an application package from an external package repository (using PackageManagement or NanoServerPackage). In this article we’ll show you how to access web from a PowerShell session via a proxy server with the authentication.

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

Update-Help

Or access an external web page:

Invoke-WebRequest http://woshub.com
If you haven’t got a direct Internet connection, the command will return a similar 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).

can't connect to the Internet from PowerShell over the authenticated proxy serverThe matter 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 proxy settings specified in the Internet Explorer. However, the WebClient class has some properties that allow you to specify both proxy settings (WebClient.Proxy) and proxy authentication data (WebClient.Credentials or WebClient.UseDefaultCredentials). Let’s consider how to use these properties of the WebClient class.

Contents:
  • Manage WinHTTP Proxy Server Settings for PowerShell
  • How to Set Proxy Authentication with PowerShell?
  • Set Proxy Server Settings in the PowerShell Profile File
  • Check Current Proxy Server Setting from PowerShell
  • Set Windows Proxy Setting Using PowerShell?

Manage WinHTTP Proxy Server Settings for PowerShell

Let’s check the current settings of the system proxy 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 settings from the Internet Explorer parameters:

netsh winhttp import proxy source=ie

or set them manually:

netsh winhttp set proxy "192.168.0.14:3128"

netsh winhttp set proxy

If proxy authentication is necessary, the error like “(407) Proxy Authentication Required” will appear when you trying to run PowerShell commands. For example, when you try to connect to your Azure subscription with the command:

Add-AzureAccount -Credential (Get-Credential)

An error occurs:

Add-AzureAccount : user_realm_discovery_failed: User realm discovery failed: The remote server returned an error: (407) Proxy Authentication Required.

How to Set Proxy Authentication with PowerShell?

Let’s consider two ways of using proxy authentication: you can use Active Directory 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 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 authenticate on the proxy server manually, run the following commands and specify user name and password in the corresponding credential 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 using Update-Help command.

Using PowerShell from behind authenticated proxy

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

Set Proxy Server Settings in the PowerShell Profile File

You can create a PowerShell profile file to automatically set 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 PS script that runs when your PowerShell.exe process starts.

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.

[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 all PS scripts to run, even from a PowerShell profile files. To allow scripts to run, you need to change your PowerShell Execution Policy. Run the command:

Set-ExecutionPolicy RemoteSigned

Save the Microsoft.PowerShell_profile.ps1 file and restart the PowerShell console window. Make sure that you can now access Web resources from a PowerShell session via a proxy without the need to run additional commands.

Check Current Proxy Server Setting from PowerShell

You can get the current proxy settings 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

Set Windows Proxy Setting Using PowerShell?

You can set proxy settings for current Windows user 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

12 comments
7
Facebook Twitter Google + Pinterest
previous post
VMWare vSphere: Managing Password Expiration Settings
next post
Reactivating Windows 10 After a Hardware Upgrade or Reinstall

Related Reading

Create Organizational Units (OU) Structure in Active Directory...

May 17, 2022

Windows Security Won’t Open or Shows a Blank...

May 17, 2022

How to Manually Install Windows Updates from CAB...

May 16, 2022

Enable or Disable MFA for Users in Azure/Microsoft...

April 27, 2022

Fix: You’ll Need a New App to Open...

April 27, 2022

12 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 http://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 _http://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
http://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=”http://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

Leave a Comment Cancel Reply

Categories

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

Recent Posts

  • Create Organizational Units (OU) Structure in Active Directory with PowerShell

    May 17, 2022
  • Windows Security Won’t Open or Shows a Blank Screen on Windows 10/ 11

    May 17, 2022
  • How to Manually Install Windows Updates from CAB and MSU Files?

    May 16, 2022
  • RDS and RemoteApp Performance Issues on Windows Server 2019/2016

    May 16, 2022
  • Deploying Software (MSI Packages) Using Group Policy

    May 12, 2022
  • Updating VMware ESXi Host from the Command Line

    May 11, 2022
  • Enable or Disable MFA for Users in Azure/Microsoft 365

    April 27, 2022
  • Fix: You’ll Need a New App to Open This Windows Defender Link

    April 27, 2022
  • How to Reset an Active Directory User Password with PowerShell and ADUC?

    April 27, 2022
  • How to Completely Uninstall Previous Versions of Office with Removal Scripts?

    April 26, 2022

Follow us

woshub.com

ad

  • Facebook
  • Twitter
  • RSS
Popular Posts
  • Installing RSAT Administration Tools on Windows 10 and 11
  • Get-ADUser: Find Active Directory User Info with PowerShell
  • How to Hide Installed Programs in Windows 10 and 11?
  • How to Find the Source of Account Lockouts in Active Directory domain?
  • Get-ADComputer: Find Computer Details in Active Directory with PowerShell
  • How to Create a UEFI Bootable USB Drive to Install Windows 10 or 7?
  • Adding Third-Party Drivers into VMWare ESXi 6.7 ISO Image
Footer Logo

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


Back To Top