Windows 自动连接 wifi 脚本

大家好,我是空哥~

背景

电脑总是自动断开连接 WIFI,未找到原因,于是写个脚本自动连接 WIFI。

命令行连接 WIFI

查看已保存的网络连接

netsh wlan show profiles 查看 WIFI

自动连接网络

netsh wlan connect name=HUAWEI_1729

在Windows操作系统中,可以使用批处理脚本(Batch Script)或PowerShell脚本来实现定期自动连接Wi-Fi网络的功能。以下是两种方法的示例:

方法1:使用批处理脚本

  1. 打开记事本,输入以下批处理命令:

    batch

    batch 复制代码
    @echo off
    set profile=YourWiFiProfileName
    netsh wlan connect name=%profile%

    YourWiFiProfileName 替换为你的Wi-Fi网络配置文件名。

  2. 保存文件 ,命名为 connectWifi.bat

  3. 设置任务计划程序(Task Scheduler)来定期运行这个批处理脚本:

    • 打开"任务计划程序"。
    • 创建新任务,设置触发器为"周期性"。
    • 在"操作"部分,选择"启动程序",并指向你的 connectWifi.bat 文件。
    • 完成设置并保存任务。

方法2:使用PowerShell脚本

  1. 打开记事本,输入以下PowerShell命令:

    powershell

    powershell 复制代码
    $profile = "YourWiFiProfileName"
    netsh wlan connect name=$profile

    YourWiFiProfileName 替换为你的Wi-Fi网络配置文件名。

  2. 保存文件 ,命名为 connectWifi.ps1

  3. 设置任务计划程序(Task Scheduler)来定期运行这个PowerShell脚本:

    • 打开"任务计划程序"。
    • 创建新任务,设置触发器为"周期性"。
    • 在"操作"部分,选择"启动程序",并指向 powershell.exe
    • 添加参数 -ExecutionPolicy Bypass -File "C:\path\to\connectWifi.ps1"(将路径替换为你的脚本实际路径)。
    • 完成设置并保存任务。

示例

bat 脚本

SH 复制代码
@echo off
set profile=HUAWEI_1729
netsh wlan connect name=%profile%

powershell 脚本

shell 复制代码
# 使用 Invoke-Expression 执行 netsh 命令并捕获输出
$output = Invoke-Expression "netsh wlan show interface"

# 显示输出结果
#Write-Host $output

# 解析输出结果以获取特定信息
# 例如,查找 "Media Connect State" 的值
$mediaConnectState = Select-String -InputObject $output -Pattern 'HUAWEI_1729'

# 显示 "Media Connect State"
#Write-Host "Media Connect State: $mediaConnectState"

$profile='HUAWEI_1729'

# 检查Wi-Fi是否已连接
if ($mediaConnectState -eq '' -or $mediaConnectState -eq $null) {
    Write-Host "Wi-Fi is not connected. Attempting to connect..."
    

    # 连接到Wi-Fi网络
    netsh wlan connect name=$profile

    # 检查连接是否成功
    if ($wifi.InterfaceStatus -ne "Connected") {
        Write-Host "Successfully connected to $profile."
    } else {
        Write-Host "Failed to connect to $profile."
    }
} else {
    Write-Host "Wi-Fi is already connected."
}

# 显示提示信息并等待用户输入
#$userInput = Read-Host "Please enter something and press Enter"

# 输出用户输入的内容
#Write-Host "You entered: $userInput"

set-ExecutionPolicy RemoteSigned

set-executionpolicy -executionpolicy unrestricted

相关推荐
Kyph34 分钟前
PCIe AVIP架构
架构
小江的记录本1 小时前
【Linux】《Linux常用命令汇总表》
linux·运维·服务器·前端·windows·后端·macos
Yeats_Liao3 小时前
RAG架构解析:检索增强生成在企业知识库中的落地路径
架构
wenzhangli73 小时前
OoderAgent Apex:基于Skills化架构的热插拔启动机制
人工智能·架构
yhole4 小时前
springboot三层架构详细讲解
spring boot·后端·架构
香香甜甜的辣椒炒肉4 小时前
Spring(1)基本概念+开发的基本步骤
java·后端·spring
ALex_zry4 小时前
微服务架构下的服务发现与注册:gRPC服务治理实战
微服务·架构·服务发现
白毛大侠5 小时前
Go Goroutine 与用户态是进程级
开发语言·后端·golang
ForteScarlet5 小时前
从 Kotlin 编译器 API 的变化开始: 2.3.20
android·开发语言·后端·ios·开源·kotlin
大阿明5 小时前
SpringBoot - Cookie & Session 用户登录及登录状态保持功能实现
java·spring boot·后端