……というタイトルの記事ですが、オリジナルの実装を自力で書くのではなく、以下のページの内容をありがたく使わせていただきます。
http://www.hsyntt.com/changing-proxy-server-settings-for-internet-explorer-using-powershell/
しかし上記のサイトはこの記事の時点では停止している(どうやら、DNSにレコードがない?)ようなので、やむを得ず、Wayback machine からサルベージを試みたのが以下のコードです。
自分の環境では、これを enable_disable_proxy_to_localhost_8080.ps1 という名前で保存して使っています。
このコードは実行するごとに自ホスト上の 8080 を proxy として使ったり、設定を無効にしたりできるので大変便利に使えます。
接続先の情報は NewProxy に記述しておけばOKです。
$regKey="HKCU:\Software\Microsoft\Windows\CurrentVersion\Internet Settings"
#Change Ip:Port to your Proxy Address:
$NewProxy = "127.0.0.1:8080"
#Gets the actual value of the proxy setting
$ActualProxy = Get-ItemProperty -path $regKey ProxyServer -ErrorAction SilentlyContinue
#Thanks to Aymeric Mouillé from blog.msdn.microsoft.com for those lines of code, I did some modifications on them
#Enables Proxy and changes Value, if Proxy is disabled
if([string]::IsNullOrEmpty($ActualProxy))
{
Set-ItemProperty -path $regKey ProxyEnable -value 1
Set-ItemProperty -path $regKey ProxyServer -value $NewProxy
Write-Host Proxy is now enabled
Write-Host New Value: $NewProxy
}
#Disables Proxy and deletes Value, if Proxy is enabled
else
{
Set-ItemProperty -path $regKey ProxyEnable -value 0
Remove-ItemProperty -path $regKey -name ProxyServer
Write-Host Proxy is now disabled
Write-Host Value has been deleted
}
#The following lines of Code prevents you from restarting I.E.. Otherwise you had to restart I.E. in order to take the registry changes
#Thanks to jvdp81 from blog.msdn.microsoft.com for those lines of code
$source=@"
[DllImport("wininet.dll")]
public static extern bool InternetSetOption(int hInternet, int dwOption, int lpBuffer, int dwBufferLength);
"@
#Create type from source
$wininet = Add-Type -memberDefinition $source -passthru -name InternetSettings
#INTERNET_OPTION_PROXY_SETTINGS_CHANGED
$wininet::InternetSetOption([IntPtr]::Zero, 95, [IntPtr]::Zero, 0)|out-null
#INTERNET_OPTION_REFRESH
$wininet::InternetSetOption([IntPtr]::Zero, 37, [IntPtr]::Zero, 0)|out-null
Read-Host Press Enter to close