PowerShell Answers

Adventures in PowerShell

About the author

Author Name is someone.
E-mail me Send mail

Recent posts

Recent comments

Don't show

Authors

Disclaimer

The opinions expressed herein are my own personal opinions and do not represent my employer's view in anyway.

© Copyright 2008

Getting through a proxy server with PowerShell

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!

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Posted by tb on Monday, January 07, 2008 3:53 AM
Permalink | Comments (0) | Post RSSRSS comment feed