1

#PSTip Validate if proxy credentials are required

I write scripts that include downloading content from the Internet. Now, I want these scripts to work even when I am behind a proxy server. There is a simple way in .NET to check if we are behind a proxy. For this purpose, we will use System.Net.WebClient .NET class.

Function Test-Proxy {
 $wc = New-Object System.Net.WebClient
 $wc.Proxy.IsBypassed("http://www.microsoft.com")
}

The Test-Proxy function returns False if you are behind a proxy server.

Note: The following example works only on PowerShell 3.0 and above.

I use this effectively along with the $PSDefaultParameterValues in PowerShell 3.0. For example, in a script to download content from Internet, I will have to set proxy credentials for the Start-BitsTransfer cmdlet. This is how I do it:

if (-not (Test-Proxy)) {
    if (-not ($PSDefaultParameterValues.ContainsKey("Start-BitsTransfer:ProxyAuthentication")) -and ($PSDefaultParameterValues.ContainsKey("Start-BitsTransfer:ProxyAuthentication"))) {
        $cred = Get-Credential -Message "Enter Proxy authentication credentials" -UserName "${env:USERDOMAIN}\${env:UserName}"
        $PSDefaultParameterValues.Add("Start-BitsTransfer:ProxyAuthentication","Basic")
        $PSDefaultParameterValues.Add("Start-BitsTransfer:ProxyCredential",$cred)
    }
}

If we place the above code snippet at the beginning of the script, it first checks if proxy authentication is required for Internet access and sets the default parameter values for Start-BitsTransfer cmdlet.

Filed in: Columns, Tips and Tricks Tags: , ,

One Response to "#PSTip Validate if proxy credentials are required"

  1. Sayan Mitra says:

    Hi Ravikanth,
    Thank you for this info. What I was looking for is the below :
    I have a windows 2003 server from where I need to test DNS connectivity (I have a few IP’s) via a Proxy IP.

    Thanks
    Sayan

Leave a Reply

Submit Comment

© 2016 PowerShell Magazine. All rights reserved. XHTML / CSS Valid.
Proudly designed by Theme Junkie.
%d bloggers like this: