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

如何在C#中正确格式化PowerShell脚本添加Windows防火墙规则?

解决C#调用PowerShell添加Windows防火墙规则的错误问题

你遇到的CS1501错误主要有两个原因:一是PowerShell.Create()方法没有接受字符串参数的重载,二是原代码里的PowerShell脚本字符串存在格式错误(包括双引号转义、多余符号、命令名空格问题)。

错误点拆解

  1. PowerShell.Create()用法错误:该方法无直接传入脚本字符串的重载,必须先创建PowerShell实例,再通过AddScript或AddCommand添加执行内容。
  2. 脚本字符串格式错误:
    • C#字符串中的双引号需要用两个双引号转义,或使用逐字字符串(@前缀)简化写法;
    • 命令名New - NetFirewallRule多了空格,正确应为New-NetFirewallRule;
    • 原代码末尾多余的');属于无效符号,需要删除。

正确实现代码

推荐两种写法,其中AddCommand方式更安全,能避免脚本注入风险:

方式1:使用AddScript执行完整脚本

Console.WriteLine("Firewall not yet configured, doing now.");
// 使用using确保PowerShell实例自动释放
using (PowerShell psInstance = PowerShell.Create())
{
    // 用@逐字字符串避免双引号转义,同时修正命令格式
    psInstance.AddScript(@"New-NetFirewallRule -DisplayName ""Allow TOR through Windows Firewall"" -Direction Inbound -Program ""C:\ProgramData\chocolatey\bin\tor.exe"" -Action Allow");
    psInstance.Invoke();
}

方式2:使用AddCommand传递参数(更推荐)

Console.WriteLine("Firewall not yet configured, doing now.");
using (PowerShell psInstance = PowerShell.Create())
{
    psInstance.AddCommand("New-NetFirewallRule")
              .AddParameter("DisplayName", "Allow TOR through Windows Firewall")
              .AddParameter("Direction", "Inbound")
              .AddParameter("Program", @"C:\ProgramData\chocolatey\bin\tor.exe")
              .AddParameter("Action", "Allow");
    psInstance.Invoke();
}

注意事项

  • 程序需要以管理员权限运行,否则修改防火墙规则会失败;
  • 建议始终用using包裹PowerShell实例,确保资源正确释放;
  • AddCommand方式将参数单独传递,比直接拼接脚本字符串更安全,能避免潜在的脚本注入问题。

内容的提问来源于stack exchange,提问作者Keifer Bly

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.24 18:52:54