首页 > 技术文章 > powershell实现代理上网

che1234 2017-07-28 15:49 原文

修改需设置代理网络环境识别方式。由原来的查找注册表项改为根据DNS后缀进行判断。

1.建立自动切换脚本
标红色的地方需根据自己的情况进行修改。
$proxyServer:改为代理服务器地址;
$cmpStr:DNS域名,可以通过ipconfig命令查看。设置需要使用代理的DNS域名,其它为禁用IE代理。

可把下面的代码复制下来,把上述2个字符串找到并替换红色对应位置,保存为“SwitchProxy.ps1”,放到C盘提示需提升权限,可以在D盘建立一个文件夹,把此文件放到文件夹中。
#代理服务器
$proxyServer = "XXX.XXX.corp.com:80"
#公司标志
$cmpStr = "XXX.XXX.COM"
#获取网卡(可加多个,如有线网卡、无线网卡)
$netAdp = gwmi -class Win32_NetworkAdapterConfiguration -filter "(Description like 'Intel%' or Description like 'Realtek%')"
#注册表位置
$regKey = "HKCU:\Software\Microsoft\Windows\CurrentVersion\Internet Settings"
$regConKey = "HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Internet Settings\Connections"
#标志位
$flagIndex = 8
$flagProxy = 2
$flagCount = 4
#注册表值
$conSet = $(Get-ItemProperty $regConKey).DefaultConnectionSettings
$slSet = $(Get-ItemProperty $regConKey).SavedLegacySettings
$proxyEnabled = $(Get-ItemProperty $regKey).ProxyEnable

if($netAdp.DNSDomain -contains $cmpStr)
{
Write-Host "IE proxy is enabling"
if($proxyEnabled -ne 1)
{
Set-ItemProperty -path $regKey -Name ProxyEnable -value 1
Set-ItemProperty -path $regKey -Name ProxyServer -value $proxyServer
}

if($($conSet[$flagIndex] -band $flagProxy) -ne $flagProxy)
{
$conSet[$flagIndex] = $conSet[$flagIndex] -bor $flagProxy
$conSet[$flagCount]++
$slSet[$flagIndex] = $slSet[$flagIndex] -bor $flagProxy
$slSet[$flagCount] += 2

Set-ItemProperty -Path $regConKey -Name DefaultConnectionSettings -Value $conSet
Set-ItemProperty -Path $regConKey -Name SavedLegacySettings -Value $slSet
}
}
else
{
Write-Host "IE proxy is disabling"
if($proxyEnabled -eq 1)
{
Set-ItemProperty -path $regKey -Name ProxyEnable -value 0
#Remove-ItemProperty -Path $regKey -Name ProxyServer
}

if($($conSet[$flagIndex] -band $flagProxy) -eq $flagProxy)
{
$flagDisableProxy = -bnot $flagProxy
$conSet[$flagIndex] = $conSet[$flagIndex] -band $flagDisableProxy
$conSet[$flagCount]++
$slSet[$flagIndex] = $slSet[$flagIndex] -band $flagDisableProxy
$slSet[$flagCount] += 2

Set-ItemProperty -Path $regConKey -Name DefaultConnectionSettings -Value $conSet
Set-ItemProperty -Path $regConKey -Name SavedLegacySettings -Value $slSet
}
}


2.用Powershell手动执行
到刚才建的目录下,用Powershell手动执行“SwitchProxy.ps1”,看看是否报错。一般会提示是否执行,需要确认。为了避免计划任务运行时的问题,可用管理员权限打开Powershell,执行 “Set-ExecutionPolicy Unrestricted”,有安全要求的可以自己弄个签名,将SwitchProxy.ps1进行签名后,改为“Set-ExecutionPolicy AllSigned”。
手动执行没问题的话,就可以进行下一步。

如果powershell 提示无法加载文件 D:\ss\SwitchProxy.ps1,因为在此系统中禁止执行脚本。 此时应该输入set-executionpolicy remotesigned 更改执行权限

 

 

还可以添加计划任务 taskschd.msc来计划执行此脚本

来源http://blog.sina.com.cn/s/blog_539576160101l6gf.html

推荐阅读