1、具体操作
- 把wireguard节点全部导入到客户端
- 创建一个名为
auto-wg.ps1的脚本,然后把下面的脚本全部粘贴进去
- 可视化调试命令
powershell.exe -ExecutionPolicy Bypass -File "你的脚本路径"
- 创建一个快捷方式——把下面的命令粘贴到目标(T)中——右键属性——点击高级——勾选用管理员身份运行
C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe -ExecutionPolicy Bypass -WindowStyle Hidden -File "你的脚本路径"
2、脚本代码
- 注意:红色部分”aliyun1″ 和”demo” 要对应你wireguard节点的名称,这里是可以自定义的,对应过来即可
# auto-wg.ps1
# 功能:
# - 启动时自动测速并优选一次 WireGuard 节点
# - 之后每隔一段时间自动再次测速(不频繁切换)
# - 只有「新节点明显更快」且「距离上次切换已超过最小间隔」时才切换
# - 切换逻辑:先卸载所有旧节点,再安装目标节点,保证不会多个同时在线
# - 托盘左键:打开 WireGuard 客户端
# - 托盘右键:打开 WireGuard 客户端 / 退出托盘助手
Add-Type -AssemblyName System.Windows.Forms
Add-Type -AssemblyName System.Drawing
# =============== 可配置区域(你主要改这里) ===============
# WireGuard 程序路径
$wgExe = "C:\Program Files\WireGuard\wireguard.exe"
# WireGuard GUI 导入后的配置目录
$wgConfigDir = "C:\Program Files\WireGuard\Data\Configurations"
# 节点列表:名字要和 WireGuard GUI 左侧列表一模一样
$nodeHosts = @{
"aliyun" = "服务器域名或IP"
"aliyun1" = "服务器域名或IP"
"vultr" = "服务器域名或IP"
}
# 每次测速发几个 ping 包
$PingCount = 5
# 自动检测间隔(秒)
$CheckIntervalSeconds = 300 # 5 分钟一轮
# 切换门槛:新节点至少要比当前快多少 ms
$SwitchImprovementThresholdMs = 30
# 两次切换之间的最小间隔时间(秒)
$MinSwitchIntervalSeconds = 900 # 15 分钟
# 当前节点状态
$script:currentNodeName = $null
$script:lastSwitchTime = $null
$script:lastCheckTime = Get-Date
$script:isChecking = $false
$script:running = $true
# =============== 工具函数 ===============
function Get-Nodes {
param(
[hashtable]$NodeHosts,
[string]$ConfigDir
)
$nodes = @()
foreach ($name in $NodeHosts.Keys) {
$confPath = Join-Path $ConfigDir ("{0}.conf.dpapi" -f $name)
if (-not (Test-Path $confPath)) {
Write-Host "⚠ 找不到配置文件:$confPath,跳过节点 $name" -ForegroundColor Yellow
continue
}
$nodes += [pscustomobject]@{
Name = $name
Host = $NodeHosts[$name]
Conf = $confPath
}
}
return $nodes
}
function Test-NodesLatency {
param(
[array]$Nodes,
[int]$PingCount
)
$results = @()
foreach ($n in $Nodes) {
Write-Host ""
$time = Get-Date -Format 'HH:mm:ss'
Write-Host "[$time] 测试 $($n.Name) ($($n.Host)) ..." -ForegroundColor Cyan
try {
$pings = Test-Connection -Count $PingCount -ComputerName $n.Host -ErrorAction Stop
}
catch {
Write-Host " 无法连通,记为 9999ms" -ForegroundColor Red
$results += [pscustomobject]@{
Name = $n.Name
Host = $n.Host
Conf = $n.Conf
Avg = 9999
}
continue
}
$avg = ($pings | Measure-Object -Property ResponseTime -Average).Average
$avg = [math]::Round($avg, 2)
Write-Host " 平均延迟:$avg ms"
$results += [pscustomobject]@{
Name = $n.Name
Host = $n.Host
Conf = $n.Conf
Avg = $avg
}
}
return $results
}
function Switch-ToNode {
param(
[pscustomobject]$TargetNode,
[array]$AllNodes,
[string]$WgExe,
[pscustomobject]$CurrentNode,
[System.Windows.Forms.NotifyIcon]$notifyIcon
)
Write-Host ""
Write-Host ">>> 准备切换到节点:$($TargetNode.Name) (延迟 $($TargetNode.Avg) ms) ..." -ForegroundColor Green
# 1)先卸载脚本管理的所有隧道服务,避免多个同时在线
Write-Host " 卸载所有旧节点服务..."
foreach ($n in $AllNodes) {
Write-Host " 卸载隧道:$($n.Name)"
& $WgExe /uninstalltunnelservice $n.Name 2>$null
}
Start-Sleep -Milliseconds 800 # 给系统一点时间处理
# 2)安装目标节点
Write-Host " 安装新节点服务:$($TargetNode.Conf)"
& $WgExe /installtunnelservice $TargetNode.Conf
# 关键:只有 ExitCode 明确是非 0 时才当失败;null 或 0 都认为成功
$exit = $LASTEXITCODE
if ($exit -ne $null -and $exit -ne 0) {
$msg = "安装新节点 $($TargetNode.Name) 失败,ExitCode = $exit,保持当前节点不变。"
Write-Host $msg -ForegroundColor Red
$notifyIcon.ShowBalloonTip(5000, "WireGuard 智能优选",
$msg, [System.Windows.Forms.ToolTipIcon]::Error)
# 回滚:如果有旧节点信息,就再装回旧节点
if ($CurrentNode -and $CurrentNode.Conf) {
Write-Host " 回滚:重新安装当前节点 $($CurrentNode.Name)..."
& $WgExe /installtunnelservice $CurrentNode.Conf 2>$null
}
return $false
}
$tip = "已切换到 $($TargetNode.Name)(约 $($TargetNode.Avg) ms)"
Write-Host ">>> $tip" -ForegroundColor Green
$notifyIcon.ShowBalloonTip(3000, "WireGuard 智能优选",
$tip, [System.Windows.Forms.ToolTipIcon]::Info)
return $true
}
function Invoke-WGSmartSwitch {
param(
[System.Windows.Forms.NotifyIcon]$notifyIcon
)
try {
$nodes = Get-Nodes -NodeHosts $nodeHosts -ConfigDir $wgConfigDir
if ($nodes.Count -eq 0) {
$msg = "没有可用节点,请检查连接名和配置目录。"
Write-Host $msg -ForegroundColor Red
$notifyIcon.ShowBalloonTip(3000, "WireGuard 智能优选", $msg,
[System.Windows.Forms.ToolTipIcon]::Error)
return
}
Write-Host "`n========== 开始测速并优选 =========="
$results = Test-NodesLatency -Nodes $nodes -PingCount $PingCount
Write-Host "`n本轮结果:"
$results | Sort-Object Avg | Format-Table
$best = $results | Sort-Object Avg | Select-Object -First 1
if ($best.Avg -ge 9999) {
$msg = "所有节点当前都不可用,本次不切换。"
Write-Host $msg -ForegroundColor Red
$notifyIcon.ShowBalloonTip(3000, "WireGuard 智能优选", $msg,
[System.Windows.Forms.ToolTipIcon]::Error)
return
}
# 找当前节点的测速结果
$current = $null
if ($script:currentNodeName) {
$current = $results | Where-Object { $_.Name -eq $script:currentNodeName } | Select-Object -First 1
}
# 情况 1:第一次运行 / 当前节点未知 / 当前节点已挂
if (-not $current -or $current.Avg -ge 9999) {
Write-Host "当前没有有效节点或当前节点不可用,直接切到最优节点 $($best.Name)。"
$ok = Switch-ToNode -TargetNode $best -AllNodes $nodes -WgExe $wgExe -CurrentNode $current -notifyIcon $notifyIcon
if ($ok) {
$script:currentNodeName = $best.Name
$script:lastSwitchTime = Get-Date
}
return
}
# 情况 2:当前节点已经是最优节点
if ($best.Name -eq $current.Name) {
Write-Host "当前节点 $($current.Name) 已是最优节点($($current.Avg) ms),不切换。"
return
}
# 情况 3:有更优节点,检查是否“足够更优”+“间隔够长”
$improvement = $current.Avg - $best.Avg
Write-Host "当前节点:$($current.Name) $($current.Avg) ms,新最优:$($best.Name) $($best.Avg) ms,提升:$improvement ms"
if ($improvement -lt $SwitchImprovementThresholdMs) {
Write-Host "提升不足 $SwitchImprovementThresholdMs ms,不值得切换,本次忽略。"
return
}
if ($script:lastSwitchTime) {
$elapsed = (Get-Date) - $script:lastSwitchTime
if ($elapsed.TotalSeconds -lt $MinSwitchIntervalSeconds) {
Write-Host "距离上次切换仅过去 $([int]$elapsed.TotalSeconds) 秒,小于最小间隔 $MinSwitchIntervalSeconds 秒,本次不切换。"
return
}
}
# 条件都满足,执行切换
$ok2 = Switch-ToNode -TargetNode $best -AllNodes $nodes -WgExe $wgExe -CurrentNode $current -notifyIcon $notifyIcon
if ($ok2) {
$script:currentNodeName = $best.Name
$script:lastSwitchTime = Get-Date
}
}
catch {
$err = $_.Exception.Message
Write-Host "执行优选时出错:$err" -ForegroundColor Red
$notifyIcon.ShowBalloonTip(3000, "WireGuard 智能优选",
"执行出错:$err", [System.Windows.Forms.ToolTipIcon]::Error)
}
}
# =============== 托盘图标 & 菜单 ===============
$notifyIcon = New-Object System.Windows.Forms.NotifyIcon
$notifyIcon.Icon = [System.Drawing.SystemIcons]::Application
$notifyIcon.Text = "WireGuard 智能优选"
$notifyIcon.Visible = $true
$menu = New-Object System.Windows.Forms.ContextMenuStrip
$menuItemOpen = $menu.Items.Add("打开 WireGuard 客户端")
$menuItemOpen.Add_Click({
try {
Start-Process -FilePath $wgExe
} catch {
[System.Windows.Forms.MessageBox]::Show(
"无法启动 WireGuard:$($_.Exception.Message)",
"启动失败",
[System.Windows.Forms.MessageBoxButtons]::OK,
[System.Windows.Forms.MessageBoxIcon]::Error
) | Out-Null
}
})
$menu.Items.Add("-") | Out-Null
$menuItemExit = $menu.Items.Add("退出托盘助手")
$menuItemExit.Add_Click({
Write-Host "收到退出指令,准备退出托盘助手..."
$script:running = $false
})
$notifyIcon.ContextMenuStrip = $menu
# 左键:打开客户端
$notifyIcon.Add_MouseClick({
param($sender, $e)
if ($e.Button -eq [System.Windows.Forms.MouseButtons]::Left) {
try {
Start-Process -FilePath $wgExe
} catch {
[System.Windows.Forms.MessageBox]::Show(
"无法启动 WireGuard:$($_.Exception.Message)",
"启动失败",
[System.Windows.Forms.MessageBoxButtons]::OK,
[System.Windows.Forms.MessageBoxIcon]::Error
) | Out-Null
}
}
})
Write-Host "WireGuard 托盘助手已启动。"
Write-Host " - 启动时自动测一次并优选线路"
Write-Host " - 之后每 $CheckIntervalSeconds 秒自动检测一次"
Write-Host " - 左键托盘:打开 WireGuard 客户端"
Write-Host " - 右键托盘:打开 WireGuard 客户端 / 退出托盘助手`n"
# 启动时先自动测速并优选一次
Invoke-WGSmartSwitch -notifyIcon $notifyIcon
# =============== 主循环 + 消息泵 ===============
while ($script:running) {
[System.Windows.Forms.Application]::DoEvents()
$now = Get-Date
$elapsed = ($now - $script:lastCheckTime).TotalSeconds
if (-not $script:isChecking -and $elapsed -ge $CheckIntervalSeconds) {
$script:isChecking = $true
try {
Invoke-WGSmartSwitch -notifyIcon $notifyIcon
}
finally {
$script:isChecking = $false
$script:lastCheckTime = Get-Date
}
}
Start-Sleep -Milliseconds 500
}
$notifyIcon.Visible = $false
$notifyIcon.Dispose()
Write-Host "托盘助手已退出。"
4、wireguard服务器配置文件路径:/etc/wireguard










