如何使用脚本通过其服务名称获取进程ID到变量 [英] How to get process id by its service name with a script to variable

查看:23
本文介绍了如何使用脚本通过其服务名称获取进程ID到变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有名为 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 实现跨平台支持.这导致 cmdlet 发生了许多以 Windows 为中心的更改,有些更改被完全排除在外.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到变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆