【转】Using PowerShell Behind a Proxy

If you access the Internet in the organization via the proxy server, by default you won’t be able to access an external webpage (Invoke-WebRequest cmdlet), update help using Update-Help cmdlet or download an application package from an external package repository (using PackageManagement or NanoServerPackage) from your PowerShell session. In this article we’ll show how to get the Internet access via proxy server with the authentication from a PowerShell session.
Let’s try to update PowerShell Help:

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:
Invoke-WebRequest: Unable to connect to the remote server
在这里插入图片描述
The matter is that PowerShell (to be more precise, .NET class System.Net.WebClient that is using these cmdlets to address the external resources over HTTP) does not use system proxy settings specified in IE. However, WebClient class has some properties that allow 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 WebClient class.

Let’s check the current settings of the system proxy in the PowerShell session:

netsh winhttp show proxy

As you can see, proxy settings are not specified

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

在这里插入图片描述
Import the proxy settings from Internet Explorer parameters:

netsh winhttp import proxy source=ie

or set them manually:

netsh winhttp set proxy "192.168.0.14:3128"

在这里插入图片描述

If proxy authentication is necessary, the error like “(407) Proxy Authentication Required” will appear when trying to run PoSh commands. Let’s consider two ways of proxy authentication.

If you are signed in using your domain account and your proxy supports NTLM/AD authentication, you can use the credentials of the current user to authenticate on the proxy server (you won’t have to enter your username/password):

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

If you have to authenticate on the proxy server manually, run the following commands and specify user name and password in the corresponding window.

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

在这里插入图片描述
Now you can try to access an external website or update the help using Update-Help command.
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值