共计 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元/年
正文完