Change Proxy settings based on connected network with PowerShell

If you work for a lot of different customers it becomes a drag to repeatedly change your proxy settings in your browser and trying to remember the different proxy servers and port configurations. While thinking about this problem I found a blog post from Jeff Wouters that addresses this problem.
In his blog he describes a great function to eliminate this problem, only it is based on PowerShell 2.0. PowerShell 3.0 has some new cmdlets that makes this task simpler.

Let’s alter this script using the PowerShell 3.0 capability’s to make it more robust. I came up with the following functions to complete this task.

Function Configure-Proxy ($Proxy, $Port)
{
# Function that actually does the configuring of the proxy settings.
Set-ItemProperty "HKCU:\Software\Microsoft\Windows\CurrentVersion\Internet Settings" -Name ProxyEnable -Value 1
Set-ItemProperty "HKCU:\Software\Microsoft\Windows\CurrentVersion\Internet Settings" -Name ProxyServer -Value $Proxy":"$Port
Set-ItemProperty "HKCU:\Software\Microsoft\Windows\CurrentVersion\Internet Settings" -Name ProxyOverride -Value "<local>"
}
 

Function Set-Proxy
{
$Customers = Import-Csv C:\Projecten\CustomerNetworks.csv
$a = Get-NetAdapter | Where-Object {$_.status -eq "Up"}
$b = $a.ifIndex
$NetworkConfig = Get-DnsClient -InterfaceIndex $b
$Match = $false
ForEach ($customer in $customers)
{
$Port = $Customer.Port
$Proxy = $Customer.Proxy
$Network = $Customer.Network

# /pre>If the network name found by the NIC matches to one in the CSV the proxy
# settings are configured by parsing the right to the Configure-Proxy function.

If ($NetworkConfig.suffix -eq "$Network")
{
Configure-Proxy $Proxy $Port
$Match = $True
}

# If no value applies, disable the proxy configuration.
elseif (!$match)
{
Set-ItemProperty "HKCU:\Software\Microsoft\Windows\CurrentVersion\Internet Settings" -Name ProxyEnable -Value 0
}
}
}

This function is using a CSV file to collect the different Proxy settings. Here is an example of how this CSV should look like.

image

If the connected network is not recognized, no proxy is used.