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

C#调用PowerShell脚本报错:无法将string转换为RunspaceMode

解决C#调用PowerShell脚本时的CS1503类型转换错误

错误原因

你遇到的CS1503错误,本质是PowerShell.Create()方法没有接受字符串的重载。你直接传入的PowerShell脚本字符串,被编译器误判为要转换为System.Management.Automation.RunspaceMode枚举类型,导致类型不匹配。

修正方案

正确的做法是先创建空的PowerShell实例,再通过AddScript()方法传入要执行的命令。同时还要修正原脚本的两个小问题:

  • 路径中的反斜杠需要转义(或者用C#逐字字符串@)
  • 原命令末尾的Action Allow:多了一个冒号,属于语法错误

修正后的代码示例

using System.Management.Automation;

// 创建PowerShell实例
PowerShell allowtorthroughwindowsfirewallinbound = PowerShell.Create();

// 添加要执行的防火墙规则命令(用逐字字符串避免转义反斜杠)
allowtorthroughwindowsfirewallinbound.AddScript(@"New-NetFirewallRule -DisplayName ""Allow TOR through Windows Firewall"" -Direction Inbound -Program C:\ProgramData\chocolatey\bin\tor.exe -Action Allow");

// 执行命令并处理结果
var results = allowtorthroughwindowsfirewallinbound.Invoke();

// 检查执行过程中的错误
if (allowtorthroughwindowsfirewallinbound.HadErrors)
{
    foreach (var error in allowtorthroughwindowsfirewallinbound.Streams.Error)
    {
        // 输出错误信息
        Console.WriteLine(error.ToString());
    }
}

额外注意事项

  • 项目需要引用System.Management.Automation程序集(可通过NuGet安装Microsoft.PowerShell.SDK包获取)
  • 修改Windows防火墙规则需要管理员权限,运行程序时需右键选择“以管理员身份运行”

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.24 05:37:03