从C#调用PowerShell脚本获取热点管理器返回null求助
问题排查与解决方案
核心原因
你遇到的返回null问题,大概率是WinRT对象无法在PowerShell SDK的宿主环境中正确序列化传递回C#。虽然控制台PowerShell能正常处理NetworkOperatorTetheringManager这类WinRT类型,但PowerShell SDK的运行上下文与控制台存在差异,直接返回WinRT对象会导致序列化失败,最终返回null。
解决方案
1. 修改PowerShell脚本,返回属性而非整个WinRT对象
将脚本改为返回包含所需属性的自定义对象,避免传递无法序列化的WinRT实例:
$connectionProfile = [Windows.Networking.Connectivity.NetworkInformation,Windows.Networking.Connectivity,ContentType=WindowsRuntime]::GetInternetConnectionProfile() if (-not $connectionProfile) { Write-Error "未找到可用的网络连接配置文件" return } $tetheringManager = [Windows.Networking.NetworkOperators.NetworkOperatorTetheringManager,Windows.Networking.NetworkOperators,ContentType=WindowsRuntime]::CreateFromConnectionProfile($connectionProfile) if (-not $tetheringManager) { Write-Error "无法创建热点管理器实例" return } # 返回包含目标属性的自定义对象 [PSCustomObject]@{ ClientCount = $tetheringManager.ClientCount MaxClientCount = $tetheringManager.MaxClientCount TetheringOperationalState = $tetheringManager.TetheringOperationalState }
2. 在C#代码中添加错误捕获
PowerShell的错误不会直接抛出.NET异常,需要手动检查错误流来排查问题:
public async Task TurnOnMobileHotspot() { const string script = @" $connectionProfile = [Windows.Networking.Connectivity.NetworkInformation,Windows.Networking.Connectivity,ContentType=WindowsRuntime]::GetInternetConnectionProfile() if (-not $connectionProfile) { Write-Error ""未找到可用的网络连接配置文件"" return } $tetheringManager = [Windows.Networking.NetworkOperators.NetworkOperatorTetheringManager,Windows.Networking.NetworkOperators,ContentType=WindowsRuntime]::CreateFromConnectionProfile($connectionProfile) if (-not $tetheringManager) { Write-Error ""无法创建热点管理器实例"" return } [PSCustomObject]@{ ClientCount = $tetheringManager.ClientCount MaxClientCount = $tetheringManager.MaxClientCount TetheringOperationalState = $tetheringManager.TetheringOperationalState }"; using var powershell = PowerShell.Create(); powershell.AddScript(script); var result = await powershell.InvokeAsync(); // 检查PowerShell执行错误 if (powershell.HadErrors) { foreach (var errorRecord in powershell.Streams.Error) { // 替换为你的日志或错误处理逻辑 Console.WriteLine($"PowerShell执行错误: {errorRecord.ToString()}"); } return; } // 处理返回结果 if (result.Any()) { var hotspotInfo = result[0].BaseObject as dynamic; Console.WriteLine($"当前连接设备数: {hotspotInfo.ClientCount}"); Console.WriteLine($"最大支持设备数: {hotspotInfo.MaxClientCount}"); Console.WriteLine($"热点状态: {hotspotInfo.TetheringOperationalState}"); } }
3. 额外排查点
- 进程位数匹配:确保你的.NET程序与PowerShell控制台位数一致(都是64位或都是32位)。32位进程可能无法正确加载部分WinRT组件。
- 移除不必要的执行策略设置:
Set-ExecutionPolicy -Scope Process -ExecutionPolicy Unrestricted在SDK调用中通常是多余的,进程级执行策略默认已允许脚本执行,可移除该语句简化代码。
内容的提问来源于stack exchange,提问作者Ivan Boganov
相关产品推荐
相关产品推荐

