You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C#调用PowerShell时Get-NetFirewallRule未被识别的问题求助

排查思路
  • 手动加载目标模块:Get-NetFirewallRule属于NetSecurity系统模块,C#启动的PowerShell会话可能未自动加载该模块。可在执行目标命令前,先执行Import-Module NetSecurity -Force;或在C#代码中通过如下方式先行加载:
    var ps = PowerShell.Create();
    ps.AddCommand("Import-Module")
      .AddArgument("NetSecurity")
      .AddParameter("Force");
    ps.Invoke();
    
  • 验证进程位数匹配:如果你的C#程序编译为32位目标平台,而本地使用的是64位PowerShell,32位环境下可能缺失部分系统自带模块(包括NetSecurity)。将C#项目的目标平台改为x64后重新测试。
  • 对比PS模块路径:在C#调用的PowerShell会话中执行$env:PSModulePath,与本地PowerShell中输出的路径对比,确认NetSecurity所在的系统路径(通常为C:\Windows\System32\WindowsPowerShell\v1.0\Modules)是否包含其中。若路径缺失,可在代码中手动追加:
    var ps = PowerShell.Create();
    ps.AddScript("$env:PSModulePath += ';C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\Modules'");
    ps.Invoke();
    
  • 确认PowerShell宿主类型:虽然版本号一致,但需区分C#调用的是Windows PowerShell(5.x)还是PowerShell Core(7+)。NetSecurity是Windows PowerShell的专属模块,若代码调用的是PowerShell Core,需切换回Windows PowerShell宿主,或使用兼容的替代命令。
  • 检查模块可用性:在C#的PowerShell会话中执行Get-Module -ListAvailable NetSecurity,确认模块是否存在。若返回空结果,说明当前环境无法识别该模块,可尝试手动复制模块文件到可识别的路径中。

内容的提问来源于stack exchange,提问作者Holger Kühn

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.11 03:16:13