跳转到内容
Guides 2 分钟阅读 1224 次浏览

在 PowerShell 中使用代理

在 PowerShell 中使用代理:Invoke-WebRequest、System.Net.WebProxy、系统代理配置以及通过脚本实现自动化。

在 PowerShell 中使用代理

在 PowerShell 中使用代理

PowerShell 中的代理

PowerShell 是 Windows 上强大的自动化工具。对于运行在企业网络中或需要匿名性的脚本来说,使用代理至关重要。

通过代理使用 Invoke-WebRequest

通过代理发起基本请求

$proxy = "http://proxy_ip:8080"
$response = Invoke-WebRequest -Uri "https://httpbin.org/ip" -Proxy $proxy
$response.Content

带身份验证

$proxy = "http://proxy_ip:8080"
$proxyCred = New-Object System.Management.Automation.PSCredential(
    "username",
    (ConvertTo-SecureString "password" -AsPlainText -Force)
)

$response = Invoke-WebRequest -Uri "https://httpbin.org/ip" `
    -Proxy $proxy `
    -ProxyCredential $proxyCred

$response.Content

Invoke-RestMethod(用于 JSON API)

$proxy = "http://proxy_ip:8080"
$result = Invoke-RestMethod -Uri "https://httpbin.org/ip" -Proxy $proxy
$result.origin  # 通过代理显示的您的 IP

System.Net.WebProxy

以编程方式配置

$webProxy = New-Object System.Net.WebProxy("http://proxy_ip:8080", $true)
$webProxy.Credentials = New-Object System.Net.NetworkCredential("user", "pass")

# 应用到 WebClient
$client = New-Object System.Net.WebClient
$client.Proxy = $webProxy
$result = $client.DownloadString("https://httpbin.org/ip")
Write-Host $result

为特定地址绕过代理

$webProxy = New-Object System.Net.WebProxy("http://proxy_ip:8080", $true)
$webProxy.BypassList = @("localhost", "*.local", "192.168.*")
$webProxy.BypassProxyOnLocal = $true

HttpClient(.NET)

对于高级场景,请使用 .NET 的 HttpClient:

$proxy = New-Object System.Net.WebProxy("http://proxy_ip:8080")
$proxy.Credentials = New-Object System.Net.NetworkCredential("user", "pass")

$handler = New-Object System.Net.Http.HttpClientHandler
$handler.Proxy = $proxy
$handler.UseProxy = $true

$client = New-Object System.Net.Http.HttpClient($handler)
$response = $client.GetStringAsync("https://httpbin.org/ip").Result
Write-Host $response

系统代理

读取当前设置

# 来自 Windows 注册表
$regPath = "HKCU:\Software\Microsoft\Windows\CurrentVersion\Internet Settings"
$proxyEnabled = (Get-ItemProperty -Path $regPath).ProxyEnable
$proxyServer = (Get-ItemProperty -Path $regPath).ProxyServer
Write-Host "Proxy enabled: $proxyEnabled"
Write-Host "Proxy server: $proxyServer"

设置系统代理

$regPath = "HKCU:\Software\Microsoft\Windows\CurrentVersion\Internet Settings"

# 启用代理
Set-ItemProperty -Path $regPath -Name ProxyEnable -Value 1
Set-ItemProperty -Path $regPath -Name ProxyServer -Value "proxy_ip:8080"

# 例外
Set-ItemProperty -Path $regPath -Name ProxyOverride -Value "localhost;*.local"

Write-Host "Proxy configured"

禁用系统代理

Set-ItemProperty -Path $regPath -Name ProxyEnable -Value 0
Write-Host "Proxy disabled"

环境变量

设置

$env:HTTP_PROXY = "http://proxy_ip:8080"
$env:HTTPS_PROXY = "http://proxy_ip:8080"
$env:NO_PROXY = "localhost,*.local"

持久化设置

[Environment]::SetEnvironmentVariable("HTTP_PROXY", "http://proxy_ip:8080", "User")
[Environment]::SetEnvironmentVariable("HTTPS_PROXY", "http://proxy_ip:8080", "User")

验证

Write-Host "HTTP_PROXY: $env:HTTP_PROXY"
Write-Host "HTTPS_PROXY: $env:HTTPS_PROXY"

脚本中的代理轮换

$proxies = @(
    "http://user:pass@proxy1:8080",
    "http://user:pass@proxy2:8080",
    "http://user:pass@proxy3:8080"
)

$urls = @(
    "https://httpbin.org/ip",
    "https://httpbin.org/headers",
    "https://httpbin.org/user-agent"
)

foreach ($url in $urls) {
    $proxy = $proxies | Get-Random
    try {
        $response = Invoke-RestMethod -Uri $url -Proxy $proxy -TimeoutSec 10
        Write-Host "OK: $url via $proxy"
        Write-Host $response
    } catch {
        Write-Host "FAIL: $url via $proxy - $($_.Exception.Message)"
    }
}

代理测试

function Test-Proxy {
    param(
        [string]$ProxyServer,
        [string]$ProxyPort,
        [string]$Username,
        [string]$Password
    )

    $proxy = "http://${ProxyServer}:${ProxyPort}"
    $cred = $null

    if ($Username) {
        $cred = New-Object System.Management.Automation.PSCredential(
            $Username,
            (ConvertTo-SecureString $Password -AsPlainText -Force)
        )
    }

    try {
        $params = @{
            Uri = "https://httpbin.org/ip"
            Proxy = $proxy
            TimeoutSec = 10
        }
        if ($cred) { $params.ProxyCredential = $cred }

        $response = Invoke-RestMethod @params
        Write-Host "OK - IP: $($response.origin)" -ForegroundColor Green
        return $true
    } catch {
        Write-Host "FAIL - $($_.Exception.Message)" -ForegroundColor Red
        return $false
    }
}

# 用法
Test-Proxy -ProxyServer "proxy_ip" -ProxyPort "8080" -Username "user" -Password "pass"

批量代理测试

$proxyList = Get-Content "proxies.txt"  # 格式:ip:port:user:pass

$results = foreach ($line in $proxyList) {
    $parts = $line.Split(":")
    $ip = $parts[0]; $port = $parts[1]
    $user = $parts[2]; $pass = $parts[3]

    $proxy = "http://${ip}:${port}"
    try {
        $cred = New-Object PSCredential($user, (ConvertTo-SecureString $pass -AsPlainText -Force))
        $resp = Invoke-RestMethod "https://httpbin.org/ip" -Proxy $proxy -ProxyCredential $cred -TimeoutSec 5
        [PSCustomObject]@{Proxy=$line; Status="OK"; IP=$resp.origin}
    } catch {
        [PSCustomObject]@{Proxy=$line; Status="FAIL"; IP="N/A"}
    }
}

$results | Format-Table -AutoSize
$results | Export-Csv "proxy_check_results.csv" -NoTypeInformation

结论

PowerShell 提供了灵活的代理使用工具:从简单的 cmdlet(Invoke-WebRequest)到完整的 .NET API。通过注册表和环境变量管理系统代理的能力,使 PowerShell 成为在 Windows 机器上自动化代理配置的理想选择。

已更新: 06.03.2026
返回分类

试用我们的代理

遍布 100+ 国家的 20,000+ 代理

support_agent
GProxy Support
Usually replies within minutes
Hi there!
Send us a message and we'll reply as soon as possible.