When we were looking at using the System.Net.WebClient class to retrieve web pages the question "how do you use this when you have to go through a proxy server and provide credentials?" came up.
A little bit of exploration with get-member and some digging in MSDN revealed that
- the System.Net.WebClient class has a proxy property that can be set to an instance of the System.Net.WebProxyClass
- the System.Net.WebProxyClass has a credentials property that can be set to an instance of any object that implements the ICredentials interface
- The class System.Net.NetworkCredential implements ICredentials
- the get-credential cmdlet returns a System.Management.Automation.PSCredential object
- the PSCredential class has a method called GetNetworkCredential that returns a System.Net.NetworkCredential object - just what we need :-)
Putting all of that together gives us this script which will ask for credentials and feed them to a proxy server.
[void][System.Reflection.Assembly]::LoadWithPartialName("System.Net")
#
# Create a proxy object
#
$proxy = new-object System.Net.WebProxy
#
# Grab some credentials and store them in the proxy object
#
$cred = get-credential
$proxy.credentials = $cred.GetNetworkCredential()
#
# Off to the web
#
$WebClient = new-object System.Net.WebClient
$WebClient.proxy = $proxy
$url = "http://www.microsoft.com"
$content = $WebClient.DownloadString($url)
It just goes to show how great the combination of PowerShell and the .Net framework is!