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

如何使用C#在局域网内的远程PC上启动应用程序

用WMI通过局域网远程启动应用程序

看起来你已经搭好了WMI远程连接的基础框架,我来帮你补全后续启动应用的完整逻辑,同时给你一些关键的注意事项:

首先是完整的实现代码:

using System.Management;

string sLogin = "Administrator";
string sPassword = "Password";
string sComputer = "192.168.201.224";

// 配置WMI连接选项
ConnectionOptions co = new ConnectionOptions();
co.Username = sLogin;
co.Password = sPassword;
co.EnablePrivileges = true;
co.Impersonation = ImpersonationLevel.Impersonate;

// 初始化管理范围并建立连接
ManagementScope ms = new ManagementScope(
    string.Format(@"\\{0}\root\CIMV2", sComputer), 
    co
);
ms.Connect();

// 准备远程启动进程的WMI类实例
ObjectGetOptions getOptions = new ObjectGetOptions();
ManagementPath processPath = new ManagementPath("Win32_Process");
ManagementClass processClass = new ManagementClass(ms, processPath, getOptions);

// 定义要启动的应用路径(必须是远程机器上的有效绝对路径)
string targetAppPath = @"C:\Windows\notepad.exe"; // 示例:远程启动记事本
object[] methodParams = { targetAppPath };

// 调用Create方法启动远程进程
object invokeResult = processClass.InvokeMethod("Create", methodParams);

// 解析启动结果:返回值为0表示成功
uint returnCode = (uint)invokeResult;
if (returnCode == 0)
{
    Console.WriteLine("应用已成功在远程机器启动!");
}
else
{
    Console.WriteLine($"启动失败,错误代码:{returnCode}");
}

重要注意事项:

  • 权限要求:你使用的远程账户(比如这里的Administrator)必须拥有目标机器的管理员权限,同时目标机器的WMI服务(Winmgmt)要处于运行状态。
  • 路径正确性:targetAppPath必须是远程机器上的绝对路径,比如要启动自定义程序,得写成@"D:\MyApps\MyProgram.exe"这种远程机器能识别的路径。
  • 防火墙配置:目标机器的防火墙需要允许WMI通信——默认涉及135端口和动态RPC端口,要是连接失败,优先检查防火墙是否放行WMI相关规则。
  • 错误处理优化:建议给ms.Connect()和InvokeMethod添加异常捕获,方便排查问题,比如:
    try
    {
        ms.Connect();
        // 后续启动逻辑
    }
    catch (ManagementException ex)
    {
        Console.WriteLine($"WMI连接出错:{ex.Message}");
    }
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 07:12:51