问题描述
我有一个名为 WinDefend
的服务,它在进程 svchost.exe
上运行还有其他许多 svchost.exe
进程,我需要找到一种方法来获取其 ID.
当我运行 tasklist/svc
时,我可以看到:
I have service named WinDefend
and it runs on process svchost.exe
There other many svchost.exe
processes and I need to find a way to get its ID.
when I run tasklist /svc
I can see:
我不知道如何才能得到它.
我找到了这个命令,但是当我尝试 select "PID"
时,它给了我一个空列.
I am not sure how can I get it.
I found this command but when I tried the select "PID"
it gave me empty column.
我需要将进程的 PID 设为变量.
I need to get the PID of the process to variable.
推荐答案
tasklist
只是返回文本,而不是具有您可以访问的属性的实际对象.您可以使用 WMI 来获取此信息:
tasklist
is just returning text, not actual objects that have properties you can access. You can use WMI to get this information instead:
$id = Get-WmiObject -Class Win32_Service -Filter "Name LIKE 'WinDefend'" |
Select-Object -ExpandProperty ProcessId
$process = Get-Process -Id $id
PowerShell Core 更新
在版本 6 中,Windows PowerShell 开始通过基于 .NET Core 的 PowerShell Core 实现跨平台支持.这导致了以 Windows 为中心的 cmdlet 中的许多更改,有些则完全被排除在外.WMI 是一种仅限 Windows 的技术,因此它的 cmdlet(例如 Get-WmiObject)没有被移植.但是,它的功能可通过 CIM cmdlet(例如 Get-CimInstance)获得,这是一个适用于 PowerShell 6+ 的版本:
In version 6, Windows PowerShell started towards cross platform support with PowerShell Core based on .NET Core. This led to many changes in cmdlets that were Windows-centric and some being left out completely. WMI is a Windows only technology, so its cmdlets (e.g. Get-WmiObject) were not ported over. However, its features are available via CIM cmdlets (e.g. Get-CimInstance) here is a version that will work on PowerShell 6+:
$id = Get-CimInstance -Class Win32_Service -Filter "Name LIKE 'WinDefend'" |
Select-Object -ExpandProperty ProcessId
$process = Get-Process -Id $id
这篇关于如何使用脚本到变量通过其服务名称获取进程 ID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!