升级到PowerShell Core 7.2后自动开启移动热点旧脚本失效,求适配方案
适配PowerShell 7+的移动热点自动开启脚本
原脚本依赖Windows PowerShell 5.1专属的WinRT类型加载机制开发,PowerShell 7+基于.NET Core 构建,不再原生支持该加载方式,因此会出现类型找不到、方法调用失败等错误。
以下为无额外依赖的兼容版本脚本,可直接在PowerShell 7+环境运行,实现相同的热点状态检测、自动开启功能:
# 适配Win10/11现代移动热点 Add-Type -AssemblyName System.Runtime.WindowsRuntime $null = [Windows.System.Launcher, Windows.System, ContentType = WindowsRuntime] $interop = [System.Runtime.InteropServices.Marshal]::GetTypedObjectForIUnknown( [System.Runtime.InteropServices.Marshal]::CreateIUnknownForObject([Windows.Networking.Connectivity.NetworkInformation]), [type]"Windows.Networking.Connectivity.INetworkInformationStatics" ) $connectionProfile = $interop.GetInternetConnectionProfile() $tetheringManagerInterop = [type]"Windows.Networking.NetworkOperators.INetworkOperatorTetheringManagerStatics" $tetheringManager = [System.Runtime.InteropServices.Marshal]::GetTypedObjectForIUnknown( [System.Runtime.InteropServices.Marshal]::CreateIUnknownForObject([Windows.Networking.NetworkOperators.NetworkOperatorTetheringManager]), $tetheringManagerInterop ).CreateFromConnectionProfile($connectionProfile) if ($tetheringManager.TetheringOperationalState -eq [Windows.Networking.NetworkOperators.TetheringOperationalState]::On) { Write-Host "Hotspot is already On!" } else { Write-Host "Hotspot is off! Turning it on" $asyncOp = $tetheringManager.StartTetheringAsync() $awaiter = $asyncOp.GetAwaiter() while (-not $awaiter.IsCompleted) { Start-Sleep -Milliseconds 100 } $result = $awaiter.GetResult() if ($result.Status -ne [Windows.Networking.NetworkOperators.NetworkOperatorTetheringOperationStatus]::Success) { Write-Host "Failed to start hotspot: $($result.Status)" } }
如果上述脚本仍存在兼容性问题,可以使用调用系统内置netsh命令的简化版本,兼容性更强:
# 检测热点状态 $status = netsh wlan show hostednetwork | Select-String -Pattern "状态\s+:\s+(\S+)" if ($status.Matches.Groups[1].Value -eq "已启动") { Write-Host "Hotspot is already On!" } else { Write-Host "Hotspot is off! Turning it on" netsh wlan start hostednetwork }
注意:如果你的设备使用的是Win10/11的现代移动热点而非旧式承载网络,需要先在系统设置的「移动热点」页面完成热点名称、密码的首次配置后,脚本即可正常运行。
内容的提问来源于stack exchange,提问作者mp3846
相关产品推荐
相关产品推荐

