本文告诉大家如何使用 WMI 通过 Process 获取这个进程传入的命令行

使用下面代码,使用 Win32_Process 拿到所有的进程,通过 WHERE 判断当前的进程,然后拿到进程传入的命令

private static string GetCommandLine(this Process process)
{
using (ManagementObjectSearcher searcher = new ManagementObjectSearcher("SELECT CommandLine FROM Win32_Process WHERE ProcessId = " + process.Id))
using (ManagementObjectCollection objects = searcher.Get())
{
return objects.Cast<ManagementBaseObject>().SingleOrDefault()?["CommandLine"]?.ToString();
}

}

获取所有的进程的命令行参数

private static void Main()
{
foreach (var process in Process.GetProcesses())
{
try
{
Console.WriteLine(process.GetCommandLine());
}
catch (Win32Exception ex) when ((uint)ex.ErrorCode == 0x80004005)
{
// Intentionally empty - no security access to the process.
}
catch (InvalidOperationException)
{
// Intentionally empty - the process exited before getting details.
}

}
}

如果不能访问 WMI 如使用的是 dotnet core 2.0 以下版本或需要通过 dotnet core 编译为 Native 就可以尝试​​不使用 WMI 在 dotnet 获取指定进程的输入命令行​

https://stackoverflow.com/a/2633674/6116637

​dotnet 获取指定进程的输入命令行​

更多 WMI 请看 ​​WMI 博客​

​.NET/C# 获取一个正在运行的进程的命令行参数 - walterlv​

我搭建了自己的博客欢迎大家访问,里面有很多新的博客。但是一旦发布了就不再更新

如果在博客看到有任何不懂的,欢迎交流,

如有不方便在博客评论的问题,可以加我 交流

dotnet 通过 WMI 获取指定进程的输入命令行_商业

本作品采用知识共享署名-非商业性使用-相同方式共享 4.0 国际许可协议进行许可。欢迎转载、使用、重新发布,但务必保留文章署名林德熙(包含链接:lindexi_lindexi_gdc#,WPF,UWP领域博主 ),不得用于商业目的,基于本文修改后的作品务必以相同的许可发布。如有任何疑问,请与我联系。