如何在VB中获取所有正在运行的进程及其命令参数

时间:2015-02-18 05:32:56

标签: vb.net

如何在VB中获取所有正在运行的进程和命令参数? 我只找到了所有进程,但找不到他们的命令行参数。

For Each OneProcess As Process In Process.GetProcesses
            ListBox1.Items.Add(OneProcess.ProcessName) '&""Environment.CommandLine)

如何获取命令行列表?

3 个答案:

答案 0 :(得分:1)

您可以使用WMI获取正在运行的进程的命令行。像这样:

    Dim searcher As New ManagementObjectSearcher("root\CIMV2", "SELECT * FROM Win32_Process")

    For Each p As ManagementObject In searcher.[Get]()
        Dim commandLine As String = p("CommandLine")
    Next

变量commandLine将为您提供用于启动进程的命令行(如果适用),如果没有从命令行启动该进程,则不执行任何操作。您可以检查Name属性(所以p("Name"))以获取您感兴趣的进程(即qw1.exe,qw2.exe等)。

您需要将其添加到代码顶部:

Imports System.Management

并添加对System.Management的引用。

答案 1 :(得分:0)

这是不稳定的(不稳定是正则表达式)方法:

此代码将为您提供一个名为outputarray的基于0的数组,该数组是netstat -aoncmd.exe的返回值。该数组有三列:

  1. 第一列是本地地址
  2. 第二列是遥远的地址
  3. 第三列是pid(进程ID)
  4. 第1部分:


     Sub Main()
                'We will need to use netstat to get two things:
                'The connection address
                'and your processes PID
                Dim CMD As New Process
                CMD.StartInfo.FileName = "CMD.exe"
                CMD.StartInfo.Arguments = "/c netstat -aon"
                CMD.StartInfo.RedirectStandardOutput = True
                CMD.StartInfo.UseShellExecute = False
                CMD.Start()
                'OutPut is our bucket that gets the spews of netstat
                Dim OutPut As String = CMD.StandardOutput.ReadToEnd
                'We will parse through Output using regex to get the address and the process pid
                Dim Pattern As String = "([\d\.:]+).+?([\d\.:]+).+\s(\d+)\s"
                Dim regex As New System.Text.RegularExpressions.Regex(Pattern,System.Text.RegularExpressions.RegexOptions.Multiline)
                'We will put the result a string array of three columns
                Dim rowcount As Long = regex.Matches(OutPut).Count
                ' output is 0-based
                Dim outputarray(0 To rowcount - 1, 0 To 2) As String
                Dim i As Long = 0
                For Each match In regex.Matches(OutPut)
                    For j = 0 To 2
                        outputarray(i, j) = match.groups(j + 1).ToString
                    Next
                    i += 1
                Next
                'Read Part 2
            End Sub
    

    第2部分:

    只需运行所有流程并将其ID与数组的最后一列进行比较,如果匹配,宾果游戏,您可以从其他两列获得远程和远程地址(正则表达式将起作用)完美地在TCP IVP4连接上。)

答案 2 :(得分:0)

我认为这是最简单的一个

Imports System.Management
...

Dim searcher As New ManagementObjectSearcher( _
  "SELECT * FROM Win32_Process WHERE Name='Notepad.exe'")

 For Each process As ManagementObject in searcher.Get()
 Console.WriteLine(process("CommandLine"))
 Next