Windows 定时任务重连 wifi

50次阅读
没有评论

共计 1603 个字符,预计需要花费 5 分钟才能阅读完成。

由于笔记本长期处于盒盖状态,wifi 可能会断,所以考虑使用定时任务自动重连。

首先创建 C:\Users\Public\my\wifi\wifi-check.ps1需要修改 wifi 名称,并手动连接过

$ssid = "xxx"
$checkInterval = 60
$keepDays = 7
$logDir = "C:\Users\Public\my\logs"
$logFile = Join-Path $logDir "wifi-check.log"

if (-not (Test-Path $logDir)) {
    New-Item -ItemType Directory -Path $logDir -Force | Out-Null
}

if (Test-Path $logFile) {
    $lastWrite = (Get-Item $logFile).LastWriteTime
    if ($lastWrite -lt (Get-Date).AddDays(-$keepDays)) {
        Clear-Content $logFile
    }
}

function Write-Log {
    param ([string]$msg)

    $time = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
    $line = "[$time] $msg"

    Write-Host $line
    Add-Content -Path $logFile -Value $line
}

Write-Log "WiFi auto-check script started (keeping logs for $keepDays days)"

while ($true) {

    Write-Log "Checking network connectivity (baidu.com)"
    $ping = Test-Connection -ComputerName "baidu.com" -Count 2 -Quiet

    if (-not $ping) {
        Write-Log "Cannot reach baidu.com, trying to connect to WiFi: $ssid"

        $profiles = netsh wlan show profiles | Select-String $ssid
        if ($profiles) {
            netsh wlan connect name="$ssid" | Out-Null
            Write-Log "Attempted to connect to WiFi: $ssid"
        } else {
            Write-Log "WiFi profile '$ssid' does not exist. Please connect once manually."
        }

    } else {
        Write-Log "Network is OK"
    }

    Start-Sleep -Seconds $checkInterval
}

手动运行测试:

powershell -NoProfile -ExecutionPolicy Bypass -File C:\Users\Public\my\wifi\wifi-check.ps1

手动运行没有异常就可以将其添加为定时任务,在系统启动时执行。

# 创建 SYSTEM 用户开机启动任务,后台运行
schtasks /create /f `
  /sc onstart `
  /ru SYSTEM `
  /rl highest `
  /tn "WiFi-Auto-Reconnect" `
  /tr "powershell.exe -NoProfile -ExecutionPolicy Bypass -WindowStyle Hidden -File C:\Users\Public\my\wifi\wifi-check.ps1"

其他命令:

# 查看任务状态
schtasks /query /tn "WiFi-Auto-Reconnect" /v /fo LIST

# 删除旧任务(如果存在)
schtasks /delete /tn "WiFi-Auto-Reconnect" /f

# 立即运行一次
schtasks /run /tn "WiFi-Auto-Reconnect"
AD:【腾讯云服务器大降价】2核4G 222元/3年 1核2G 38元/年
正文完
 0
阿蛮君
版权声明:本站原创文章,由 阿蛮君 于2026-02-02发表,共计1603字。
转载说明:除特殊说明外本站文章皆由CC-4.0协议发布,转载请注明出处。
评论(没有评论)
Copyright © 2023-2026 阿蛮君博客 湘ICP备2023001393号
本网站由 亿信互联 提供云计算服务 | 又拍云CDN 提供安全防护和加速服务
Powered by Wordpress  Theme by Puock