如何在PowerShell或C#中获取进程的命令行信息

vic*_*woo 59 c# powershell command process

例如:如果我跑notepad.exe c:\autoexec.bat,

我怎样才能c:\autoexec.batGet-Process notepadPowerShell中?

或者我怎样才能c:\autoexec.batProcess.GetProcessesByName("notepad");C#中?

Ans*_*ers 107

在PowerShell中,您可以通过WMI获取进程的命令行:

$process = "notepad.exe"
Get-WmiObject Win32_Process -Filter "name = '$process'" | Select-Object CommandLine
Run Code Online (Sandbox Code Playgroud)

请注意,您需要管理员权限才能访问有关在其他用户的上下文中运行的进程的信息.作为普通用户,只有在您自己的上下文中运行的进程才能看到它.

  • @mbrownnyc如果对远程计算机运行`Get-WmiObject`(使用`-ComputerName`参数),使用`-Filter`对远程主机进行过滤,减少通过网络传输的数据量(从而提高性能) ).在从远程主机获取所有*WMI数据之后,在本地使用`Where-Object`过滤器.但是,在本地运行`Get-WmiObject`时没有什么区别,就像在这种情况下一样.另请注意,where where property <op> value`的语法仅适用于PowerShell v3或更高版本.在此之前,您必须使用`where {$ _.property <op> value}`. (7认同)
  • 这也有一个权限方面.Powershell流程需要具有至少与目标流程等效的权限.因此,常规的Powershell会话将无法获得运行升级的进程的此类信息(例如,作为管理员).在这种情况下,CommandLine(响应)将只是空白. (5认同)
  • 为了避免长行截断,您还可以使用`| fl` 或 `| ft -auto`([来自此处](http://stackoverflow.com/a/13735900/344541)) (3认同)
  • @CJBS准确地说,您需要管理员权限才能访问有关在另一个用户的上下文中运行的进程的信息.作为普通用户,只有在您自己的上下文中运行的进程才能看到它. (2认同)
  • 该值仍然被截断为一定长度的字符.您可以通过将结果传递给"out-string -Width 2000"或类似的东西来解决它. (2认同)
  • 这并没有花费太多时间来弄清楚,但是为了节省一些键击,如果你已经拥有进程ID(比如查看CPU使用情况等),你可以使用`"processid = 1234"` - 我用它来做看看哪个网站在我们的服务器上流氓(并且有200个`w3wp.exe`进程) (2认同)

Psy*_*ata 22

这个答案非常好,但是对于未来的防护和未来的帮助,除非你使用相当旧的powershell(在这种情况下我建议更新!)Get-WMIObject已经被Get-CimInstance取代了Hey Scripting Guy参考

试试这个

$process = "notepad.exe"
Get-CimInstance Win32_Process -Filter "name = '$process'" | select CommandLine 
Run Code Online (Sandbox Code Playgroud)

  • 注意,对于“ Get-CimInstance Win32_Process”,“名称”包括.exe扩展名。不同于`Get-Process`。 (2认同)

Jar*_*ach 6

我正在使用 powershell 7.1,这似乎现在作为脚本属性内置到进程对象中:

> (Get-Process notepad)[0].CommandLine
"C:\WINDOWS\system32\notepad.exe"
Run Code Online (Sandbox Code Playgroud)

有趣的是,您可以查看它的实现并看到它部分使用了来自 PsychoData 的答案:

($process | Get-Member -Name CommandLine).Definition
System.Object CommandLine {get=
                        if ($IsWindows) {
                            (Get-CimInstance Win32_Process -Filter "ProcessId = $($this.Id)").CommandLine
                        } elseif ($IsLinux) {
                            Get-Content -LiteralPath "/proc/$($this.Id)/cmdline"
                        }
                    ;}
Run Code Online (Sandbox Code Playgroud)

在进程上运行 Get-Member 表明它是System.Diagnostics.Process 的一个实例,但它有几个脚本化的属性。

其他属性是 FileVersion、Path、Product 和 ProductVersion。


Mar*_*rty 5

如果将以下代码放入 powershell $profile 文件中,则可以永久扩展“process”对象类并使用“CommandLine”属性

例子:

get-process notepad.exe | select-object ProcessName, CommandLine
Run Code Online (Sandbox Code Playgroud)

代码:

$TypeData = @{
    TypeName = 'System.Diagnostics.Process'
    MemberType = 'ScriptProperty'
    MemberName = 'CommandLine'
    Value = {(Get-CimInstance Win32_Process -Filter "ProcessId = $($this.Id)").CommandLine}
}
Update-TypeData @TypeData
Run Code Online (Sandbox Code Playgroud)