Created
January 18, 2018 21:39
-
-
Save mikeperri/36e656f28e42aa9cee18ce88361f6c16 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
param( | |
[switch]$Enable, | |
[switch]$Disable, | |
$ProxyServer = "localhost", | |
$ProxyPort = "8080" | |
) | |
$Path = "HKCU:\Software\Microsoft\Windows\CurrentVersion\Internet Settings" | |
$Proxy = "$($ProxyServer):$($ProxyPort)" | |
$ErrorActionPreference = "stop" | |
# This will happen automatically some time after the registry is updated, but we can call this DLL function to make it instant. | |
function Refresh-System | |
{ | |
$signature = @' | |
[DllImport("wininet.dll", SetLastError = true, CharSet=CharSet.Auto)] | |
public static extern bool InternetSetOption(IntPtr hInternet, int dwOption, IntPtr lpBuffer, int dwBufferLength); | |
'@ | |
$INTERNET_OPTION_SETTINGS_CHANGED = 39 | |
$INTERNET_OPTION_REFRESH = 37 | |
$type = Add-Type -MemberDefinition $signature -Name wininet -Namespace pinvoke -PassThru | |
$a = $type::InternetSetOption(0, $INTERNET_OPTION_SETTINGS_CHANGED, 0, 0) | |
$b = $type::InternetSetOption(0, $INTERNET_OPTION_REFRESH, 0, 0) | |
return $a -and $b | |
} | |
function Get-ProxyEnabled | |
{ | |
Try | |
{ | |
$Key = Get-ItemProperty -Path $Path -Name ProxyEnable | |
return $Key.ProxyEnable -eq 1 | |
} | |
Catch [System.Management.Automation.PSArgumentException] | |
{ | |
# This handles the case where the registry key does not exist. | |
return $False | |
} | |
} | |
function Enable-Proxy | |
{ | |
Set-ItemProperty -Path $Path -Name ProxyEnable -Value 1 #Enable the explicit proxy | |
Set-ItemProperty -Path $Path -Name ProxyServer -Value $Proxy #Configure the server settings | |
echo "Enabled proxy" | |
} | |
function Disable-Proxy | |
{ | |
Set-ItemProperty -Path $Path -Name ProxyEnable -Value 0 #Disable the explicit proxy | |
Try | |
{ | |
Remove-ItemProperty -Path $Path -Name ProxyServer #Clear the server settings | |
} | |
Catch [System.Management.Automation.PSArgumentException] | |
{ | |
# This handles the case where the registry key does not exist. | |
} | |
echo "Disabled proxy" | |
} | |
$ProxyEnabled = Get-ProxyEnabled | |
if ($Enable) { | |
Enable-Proxy | |
} elseIf ($Disable) { | |
Disable-Proxy | |
} elseIf ($ProxyEnabled) { | |
Disable-Proxy | |
} else { | |
Enable-Proxy | |
} | |
$RefreshSuccess = Refresh-System | |
if ($RefreshSuccess) { | |
echo "Refreshed internet settings" | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment