如何用Microsoft.Management.Infrastructure替代System.Management实现远程CMD执行
使用Microsoft.Management.Infrastructure替代System.Management实现远程执行CMD命令
前置准备
首先需要通过NuGet安装Microsoft.Management.Infrastructure包,这是微软推荐的新一代WMI管理库,相比System.Management具备更好的性能与可靠性。
转换后的代码实现
using Microsoft.Management.Infrastructure; using System; public static void RemoteExecute(string cmd, string wks) { // 创建远程CIM会话,替代原有的ManagementScope var sessionOptions = new CimSessionOptions(); using var cimSession = CimSession.Create(wks, sessionOptions); // 定义Win32_Process类的WMI路径 var processClassPath = new CimInstancePath("Win32_Process", @"root\cimv2"); // 构造Create方法的输入参数:Win32_Process.Create方法需要CommandLine作为核心参数 var parameters = new CimMethodParametersCollection(); parameters.Add(CimMethodParameter.Create("CommandLine", cmd, CimType.String, CimFlags.In)); // 远程调用Win32_Process的Create方法 var result = cimSession.InvokeMethod(processClassPath, "Create", parameters); // 可选:验证执行结果(返回值0代表执行成功) if ((uint)result.ReturnValue.Value == 0) { Console.WriteLine($"命令执行成功,生成进程ID: {result.OutParameters["ProcessId"].Value}"); } else { Console.WriteLine($"命令执行失败,错误码: {result.ReturnValue.Value}"); } }
核心差异说明
- 会话管理:用
CimSession替代原有的ManagementScope,CimSession支持更灵活的连接配置,比如自定义身份验证、超时设置等。 - 参数传递:MI库要求显式构造参数集合,明确指定参数类型与方向(输入/输出),比System.Management的数组传参方式更清晰可控。
- 结果处理:
InvokeMethod返回的CimMethodResult直接包含执行返回值与输出参数(如生成的进程ID),便于快速验证执行状态。
注意事项
- 确保远程工作站的**Windows Management Instrumentation (WMI)**服务处于运行状态。
- 执行代码的账户需具备远程工作站的管理员权限,且防火墙允许WMI通信(默认端口为5985/5986,对应HTTP/HTTPS协议)。
- 若需使用非当前账户身份验证,可在
CimSessionOptions中设置DestinationCredentials属性指定用户名与密码。
内容的提问来源于stack exchange,提问作者Giorgio Fazzi
相关产品推荐
相关产品推荐

