Windows 10 中 CMD 和 PowerShell 临时配置代理

在 Windows 10 系统中,我们经常需要为命令行工具配置代理以访问外部资源。本文介绍如何在 CMD 和 PowerShell 中临时设置代理。

CMD 中配置代理

在 CMD 中,我们通过设置环境变量来配置代理。

HTTP 代理

1
2
set http_proxy=http://proxy_server:port
set https_proxy=http://proxy_server:port

SOCKS 代理

1
2
3
set http_proxy=socks5://proxy_server:port
set https_proxy=socks5://proxy_server:port
set all_proxy=socks5://proxy_server:port

统一代理设置(推荐)

1
2
3
4
# 使用 all_proxy 可以同时设置 HTTP、HTTPS 等多种协议的代理
set all_proxy=http://proxy_server:port
# 或使用 SOCKS5
set all_proxy=socks5://proxy_server:port

带用户名和密码的代理

1
2
set http_proxy=http://username:password@proxy_server:port
set https_proxy=http://username:password@proxy_server:port

示例

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
Microsoft Windows [版本 10.0.19045.6332]
(c) Microsoft Corporation。保留所有权利。

C:\Users\Administrator>curl ip.sb
122.233.44.16

C:\Users\Administrator>set http_proxy=socks5://127.0.0.1:7891

C:\Users\Administrator>set https_proxy=socks5://127.0.0.1:7891

C:\Users\Administrator>curl ip.sb
3.112.223.181

查看当前代理设置

1
2
echo %http_proxy%
echo %https_proxy%

取消代理设置

1
2
set http_proxy=
set https_proxy=

PowerShell 中配置代理

PowerShell 提供了多种方式来配置代理。

使用环境变量

1
2
$env:http_proxy="proxy_proto://proxy_server:port"
$env:https_proxy="http://proxy_server:port"

示例

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
PowerShell 7.5.3
Loading personal and system profiles took 1538ms.
PS C:\Users\Administrator> curl ip.sb
122.233.44.16
PS C:\Users\Administrator> $Env:http_proxy="socks5://127.0.0.1:7891"
PS C:\Users\Administrator> $Env:https_proxy="socks5://127.0.0.1:7891"
PS C:\Users\Administrator> curl ip.sb
3.112.223.181
PS C:\Users\Administrator> $env:http_proxy
socks5://127.0.0.1:7891

查看当前代理设置

1
2
3
# 查看环境变量
$env:http_proxy
$env:https_proxy

取消代理设置

1
2
3
4
5
6
7
# 清除环境变量
Remove-Item Env:http_proxy
Remove-Item Env:https_proxy

# 或
$env:http_proxy=$null
$env:https_proxy=$null

注意事项

  1. 临时性:通过命令行设置的环境变量仅在当前会话中有效,关闭窗口后失效

  2. 优先级:某些工具有自己的代理配置,可能会覆盖环境变量设置

  3. 无代理列表:如需要排除某些地址不走代理,可设置 no_proxy 环境变量:

    1
    
    set no_proxy=localhost,127.0.0.1,.local
    
  4. 代理协议:通常使用 HTTP 代理即可,即使是 HTTPS 连接也使用 http:// 前缀

  5. 特殊字符:如果密码包含特殊字符,需要进行 URL 编码

永久配置代理

如果需要永久配置代理,可以:

  • 在系统环境变量中设置
  • 在 PowerShell 配置文件中添加设置命令
  • 使用各工具自己的配置文件

但通常建议按需临时配置,避免影响不需要代理的应用。

使用 Hugo 构建
主题 StackJimmy 设计