自动配置代理
- 编辑
$PROFILE: C:\Users\zmy_1\Documents\PowerShell\Microsoft.PowerShell_profile.ps1
function Get-SystemProxyConfig {
$regPath = "HKCU:\Software\Microsoft\Windows\CurrentVersion\Internet Settings"
$settings = Get-ItemProperty -Path $regPath -ErrorAction SilentlyContinue
if ($settings.ProxyEnable -ne 1) {
return [PSCustomObject]@{
Enabled = $false
Address = $null
Type = $null
}
}
$proxyAddress = $settings.ProxyServer
$proxyType = if ($proxyAddress -match "socks=") {
"SOCKS"
$proxyAddress = $proxyAddress -replace ".*socks=([^;]+).*", '$1'
} elseif ($proxyAddress -match "^https://") {
"HTTPS"
} else {
"HTTP"
}
[PSCustomObject]@{
Enabled = $true
Address = $proxyAddress
Type = $proxyType
}
}
function Sync-ProxyAutomatically {
$systemProxy = Get-SystemProxyConfig
$envProxy = $env:HTTPS_PROXY ?? $env:HTTP_PROXY ?? $null
if (-not $systemProxy.Enabled) {
if ($envProxy) {
$env:HTTP_PROXY = $null
$env:HTTPS_PROXY = $null
Write-Host "🔄 已清除环境变量(系统代理已禁用)" -ForegroundColor Yellow
}
return
}
$correctUrl = "$($systemProxy.Type.ToLower())://$($systemProxy.Address)"
if ($envProxy -ne $correctUrl) {
$env:HTTP_PROXY = $correctUrl
$env:HTTPS_PROXY = $correctUrl
Write-Host "🔄 已同步环境变量: $correctUrl" -ForegroundColor Green
}
}
function Show-ProxyStatus {
Sync-ProxyAutomatically
$systemProxy = Get-SystemProxyConfig
$envProxy = $env:HTTPS_PROXY ?? $env:HTTP_PROXY ?? $null
Write-Host "============ 代理状态 ============" -ForegroundColor Cyan
Write-Host " $('系统代理: ' + $(if($systemProxy.Enabled){'🟢 已启用'}else{'🔴 未启用'}))"
if ($systemProxy.Enabled) {
Write-Host " 类型: $($systemProxy.Type)"
Write-Host " 地址: $($systemProxy.Address)"
}
Write-Host
Write-Host " $('环境变量: ' + $(if($envProxy){'🟡 已同步'}else{'⚪ 未设置'}))"
if ($envProxy) {
Write-Host " 当前: $($envProxy)"
}
Write-Host "==================================" -ForegroundColor Cyan
}
function Invoke-ProxyEnable {
$proxy = Get-SystemProxyConfig
if (-not $proxy.Enabled) {
Write-Host "❌ 错误:系统代理未启用!" -ForegroundColor Red
return
}
$url = "$($proxy.Type.ToLower())://$($proxy.Address)"
$env:HTTP_PROXY = $url
$env:HTTPS_PROXY = $url
Write-Host "✅ 已手动设置环境变量: $url" -ForegroundColor Green
}
function Invoke-ProxyDisable {
$env:HTTP_PROXY = $null
$env:HTTPS_PROXY = $null
Write-Host "✅ 已清除代理环境变量" -ForegroundColor Green
}
Remove-Item alias:pxs -ErrorAction SilentlyContinue
Remove-Item alias:pxe -ErrorAction SilentlyContinue
Remove-Item alias:pxd -ErrorAction SilentlyContinue
Set-Alias pxs Show-ProxyStatus
Set-Alias pxe Invoke-ProxyEnable
Set-Alias pxd Invoke-ProxyDisable