Windows OS Hub
  • Windows Server
    • Windows Server 2016
    • Windows Server 2012 R2
    • Windows Server 2012
    • Windows Server 2008 R2
    • SCCM
  • Active Directory
    • Group Policies
  • Windows Clients
    • Windows 10
    • Windows 8
    • Windows 7
    • MS Office
    • Outlook
  • Virtualization
    • VMWare
    • Hyper-V
  • PowerShell
  • Exchange
  • Home
  • About

Windows OS Hub

  • Windows Server
    • Windows Server 2016
    • Windows Server 2012 R2
    • Windows Server 2012
    • Windows Server 2008 R2
    • SCCM
  • Active Directory
    • Group Policies
  • Windows Clients
    • Windows 10
    • Windows 8
    • Windows 7
    • MS Office
    • Outlook
  • Virtualization
    • VMWare
    • Hyper-V
  • PowerShell
  • Exchange

 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

9 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

Checking User Logon History in Active Directory Domain...

January 22, 2021

Windows 10: No Internet Connection After Connecting to...

January 13, 2021

Updating the PowerShell Version on Windows

December 24, 2020

Restoring Deleted Active Directory Objects/Users

December 21, 2020

Auditing Weak Passwords in Active Directory

December 14, 2020

9 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
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

Leave a Comment Cancel Reply

Categories

  • Active Directory
  • Group Policies
  • Exchange
  • Windows 10
  • Windows 8
  • Windows 7
  • Windows Server 2016
  • Windows Server 2012 R2
  • Windows Server 2008 R2
  • PowerShell
  • VMWare
  • MS Office

Recent Posts

  • Preparing Windows for Adobe Flash End of Life on December 31, 2020

    January 22, 2021
  • Checking User Logon History in Active Directory Domain with PowerShell

    January 22, 2021
  • How to Disable/Remove Thumbs.db File on Network Folders in Windows?

    January 21, 2021
  • MS SQL Server 2019 Installation Guide: Basic Settings and Recommendations

    January 19, 2021
  • USB Device Passthrough (Redirect) to Hyper-V Virtual Machine

    January 15, 2021
  • Windows 10: No Internet Connection After Connecting to VPN Server

    January 13, 2021
  • Updating the PowerShell Version on Windows

    December 24, 2020
  • How to Enable and Configure User Disk Quotas in Windows?

    December 23, 2020
  • Restoring Deleted Active Directory Objects/Users

    December 21, 2020
  • Fix: Search Feature in Outlook is Not Working

    December 18, 2020

Follow us

woshub.com
  • Facebook
  • Twitter
  • RSS
Popular Posts
  • Get-ADUser: Getting Active Directory Users Info via PowerShell
  • Install RSAT Feature on Demand on Windows 10 1809 and Later
  • How to Create a UEFI Bootable USB Drive to Install Windows 10 or 7?
  • Managing Printers and Drivers with PowerShell in Windows 10 / Server 2016
  • Get-ADComputer: Find Computer Details in Active Directory with PowerShell
  • How to Find the Source of Account Lockouts in Active Directory domain?
  • PSWindowsUpdate: Managing Windows Updates from PowerShell
Footer Logo

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


Back To Top