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
相关产品推荐
相关产品推荐

