- Finding the process ID
- Task Manager
- The tasklist command
- TList utility
- The .tlist debugger command
- PowerShell Get-Process command
- CSRSS and user-mode drivers
- Find process windows command
- Syntax
- Parameters
- Remarks
- Examples
- Управление процессами с помощью командлетов Process Managing Processes with Process Cmdlets
- Получение процессов (Get-Process) Getting Processes (Get-Process)
- Остановка процессов (Stop-Process) Stopping Processes (Stop-Process)
- Остановка всех остальных сеансов Windows PowerShell Stopping All Other Windows PowerShell Sessions
- Запуск, отладка и ожидание процессов Starting, Debugging, and Waiting for Processes
Finding the process ID
Each process running in Windows is assigned a unique decimal number called the process ID (PID). This number is used in a number of ways, for example to specify the process when attaching a debugger to it.
This topic describes how you can determine the PID for a given app using Task Manager, the tasklist Windows command, the TList utility, or the debugger.
Task Manager
Task Manager can be opened in a number of ways, but the simplest is to select Ctrl+Alt+Delete, and then select Task Manager.
In Windows 10, first click More details to expand the information displayed. From the Processes tab, select the Details tab to see the process ID listed in the PID column.
Click on any column name to sort. You can right click a process name to see more options for a process.
Some kernel errors may cause delays in Task Manager’s graphical interface.
The tasklist command
Use the built in Windows tasklist command from a command prompt to display all processes, their PIDs, and a variety of other details.
Use tasklist /? to display command line help.
TList utility
Task List Viewer (TList), or tlist.exe, is a command-line utility that displays the list of tasks, or user-mode processes, currently running on the local computer. TList is included in the Debugging Tools for Windows. For information on how to download and install the debugging tools, see Download Debugging Tools for Windows.
If you installed the Windows Driver Kit in the default directory on a 64 bit PC, the debugging tools are located here:
C:\Program Files (x86)\Windows Kits\10\Debuggers\x64\
When you run TList from the command prompt, it will display a list of all the user-mode processes in memory with a unique PID number. For each process, it shows the PID, process name, and, if the process has a window, the title of that window.
For more information, see TList.
The .tlist debugger command
If there’s already a user-mode debugger running on the system in question, the .tlist (List Process IDs) command will display a list of all PIDs on that system.
PowerShell Get-Process command
To work with automation scripts, use the Get-Process PowerShell command. Specify a specific process name, to see the process ID for that process.
For more information, see Get-Process.
CSRSS and user-mode drivers
To debug a user-mode driver running on another computer, debug the Client Server Run-Time Subsystem (CSRSS) process. For more information, see Debugging CSRSS.
Find process windows command
Searches for a string of text in a file or files, and displays lines of text that contain the specified string.
Syntax
Parameters
Parameter | Description |
---|---|
/v | Displays all lines that don’t contain the specified . |
/c | Counts the lines that contain the specified and displays the total. |
/n | Precedes each line with the file’s line number. |
/i | Specifies that the search is not case-sensitive. |
[/off[line]] | Doesn’t skip files that have the offline attribute set. |
Required. Specifies the group of characters (enclosed in quotation marks) that you want to search for. | |
[ :][ |
]
Remarks
If you don’t use /i, this command searches for exactly what you specify for string. For example, this command treats the characters a and A differently. If you use /i, however, the search becomes non-case-sensitive, and it treats a and A as the same character.
If the string you want to search for contains quotation marks, you must use double quotation marks for each quotation mark contained within the string (for example, «»This string contains quotation marks»»).
If you omit a file name, this command acts as a filter, taking input from the standard input source (usually the keyboard, a pipe (|), or a redirected file) and then displays any lines that contain string.
You can type parameters and command-line options for the find command in any order.
You can’t use wildcards (* and ?) in file names or extensions that you specify while using this command. To search for a string in a set of files that you specify with wildcards, you can use this command within a for command.
If you use /c and /v in the same command line, this command displays a count of the lines that don’t contain the specified string. If you specify /c and /n in the same command line, find ignores /n.
This command doesn’t recognize carriage returns. When you use this command to search for text in a file that includes carriage returns, you must limit the search string to text that can be found between carriage returns (that is, a string that is not likely to be interrupted by a carriage return). For example, this command doesn’t report a match for the string tax file if a carriage return occurs between the words tax and file.
Examples
To display all lines from pencil.ad that contain the string pencil sharpener, type:
To find the text, «The scientists labeled their paper for discussion only. It is not a final report.» in the report.doc file, type:
To search for a set of files, you can use the find command within the for command. To search the current directory for files that have the extension .bat and that contain the string PROMPT, type:
To search your hard disk to find and display the file names on drive C that contain the string CPU, use the pipe (|) to direct the output of the dir command to the find command as follows:
Because find searches are case-sensitive and dir produces uppercase output, you must either type the string CPU in uppercase letters or use the /i command-line option with find.
Управление процессами с помощью командлетов Process Managing Processes with Process Cmdlets
Командлеты Process в Windows PowerShell позволяют управлять локальными и удаленными процессами в Windows PowerShell. You can use the Process cmdlets in Windows PowerShell to manage local and remote processes in Windows PowerShell.
Получение процессов (Get-Process) Getting Processes (Get-Process)
Для получения процессов, запущенных на локальном компьютере, выполните командет Get-Process без параметров. To get the processes running on the local computer, run a Get-Process with no parameters.
Отдельные процессы можно получить, указав их имена или идентификаторы. You can get particular processes by specifying their process names or process IDs. Следующая команда возвращает процесс Idle: The following command gets the Idle process:
То, что в некоторых ситуациях командлеты не возвращают данные, является нормальным. Однако если при указании процесса по его идентификатору Get-Process не находит совпадений, он выдает ошибку, так как стандартной целью является получение известного выполняющегося процесса. Although it is normal for cmdlets to return no data in some situations, when you specify a process by its ProcessId, Get-Process generates an error if it finds no matches, because the usual intent is to retrieve a known running process. Если процесс с указанным идентификатором отсутствует, весьма вероятно, что идентификатор неправильный или нужный процесс уже завершился: If there is no process with that Id, it is likely that the Id is incorrect or that the process of interest has already exited:
Параметр Name командлета Get-Process можно использовать для указания подмножества процессов на основе имени процесса. You can use the Name parameter of the Get-Process cmdlet to specify a subset of processes based on the process name. Параметр Name может принимать несколько имен в виде списка с разделителями-запятыми и поддерживает использование подстановочных знаков, что позволяет задавать шаблоны имен. The Name parameter can take multiple names in a comma-separated list and it supports the use of wildcards, so you can type name patterns.
Например, следующая команда возвращает процессы, имена которых начинаются с «ex.». For example, the following command gets process whose names begin with «ex.»
Поскольку класс System.Diagnostics.Process .NET является основой для процессов Windows PowerShell, он удовлетворяет некоторым соглашениям, используемым System.Diagnostics.Process. Because the .NET System.Diagnostics.Process class is the foundation for Windows PowerShell processes, it follows some of the conventions used by System.Diagnostics.Process. Одно из таких соглашений требует, чтобы имя процесса для исполняемого файла никогда не содержало «.exe» в конце имени этого файла. One of those conventions is that the process name for an executable never includes the «.exe» at the end of the executable name.
Get-Process также принимает несколько значений для параметра Name. Get-Process also accepts multiple values for the Name parameter.
Параметр ComputerName командлета Get-Process можно использовать для получения процессов на удаленных компьютерах. You can use the ComputerName parameter of Get-Process to get processes on remote computers. Например, следующая команда получает процессы PowerShell на локальном (представленным «localhost») и двух удаленных компьютерах. For example, the following command gets the PowerShell processes on the local computer (represented by «localhost») and on two remote computers.
Имена компьютеров в этих данных не указаны, однако они хранятся в свойстве MachineName объектов процесса, возвращаемых Get-Process. The computer names are not evident in this display, but they are stored in the MachineName property of the process objects that Get-Process returns. Следующая команда использует командлет Format-Table для отображения свойств ID, ProcessName и MachineName (ComputerName) объектов процесса. The following command uses the Format-Table cmdlet to display the process ID, ProcessName and MachineName (ComputerName) properties of the process objects.
Эта более сложная команда добавляет в стандартные отображаемые данные Get-Process свойство MachineName. This more complex command adds the MachineName property to the standard Get-Process display.
Остановка процессов (Stop-Process) Stopping Processes (Stop-Process)
Windows PowerShell позволяет гибко выводить списки процессов, но как обстоят дела с остановкой процесса? Windows PowerShell gives you flexibility for listing processes, but what about stopping a process?
Командлет Stop-Process принимает имя или идентификатор, указывающие останавливаемый процесс. The Stop-Process cmdlet takes a Name or Id to specify a process you want to stop. Возможность остановки процессов зависит от ваших разрешений. Your ability to stop processes depends on your permissions. Некоторые процессы остановить нельзя. Some processes cannot be stopped. Например, при попытке остановить неактивный процесс возникает ошибка: For example, if you try to stop the idle process, you get an error:
Можно также принудительно вывести запрос с помощью параметра Confirm . You can also force prompting with the Confirm parameter. Он особенно удобен при использовании подстановочного знака в имени процесса, так как случайно может быть определено соответствие с некоторыми процессами, которые не нужно останавливать: This parameter is particularly useful if you use a wildcard when specifying the process name, because you may accidentally match some processes you do not want to stop:
Сложную обработку процессов можно реализовать с помощью командлетов фильтрации объектов. Complex process manipulation is possible by using some of the object filtering cmdlets. Так как объект Process имеет свойство Responding, которое равно true, если он перестал отвечать, вы можете остановить все неотвечающие приложения с помощью следующей команды: Because a Process object has a Responding property that is true when it is no longer responding, you can stop all nonresponsive applications with the following command:
Аналогичный подход возможен и в других ситуациях. You can use the same approach in other situations. Предположим, например, что приложение дополнительной области уведомлений запускается автоматически при открытии другого приложения. For example, suppose a secondary notification area application automatically runs when users start another application. Эта процедура может работать неправильно в сеансах служб терминалов, однако вам все равно нужно сохранить ее в сеансах, выполняемых в консоли физического компьютера. You may find that this does not work correctly in Terminal Services sessions, but you still want to keep it in sessions that run on the physical computer console. Сеансы, подключенные к рабочему столу физического компьютера, всегда имеют идентификатор сеанса 0, поэтому можно остановить все экземпляры процесса, находящиеся в других сеансах, с помощью Where-Object и SessionId процесса: Sessions connected to the physical computer desktop always have a session ID of 0, so you can stop all instances of the process that are in other sessions by using Where-Object and the process, SessionId :
Командлет Stop-Process не использует параметр ComputerName. The Stop-Process cmdlet does not have a ComputerName parameter. Поэтому для выполнения команды остановки процесса на удаленном компьютере необходимо использовать командлет Invoke-Command. Therefore, to run a stop process command on a remote computer, you need to use the Invoke-Command cmdlet. Например, чтобы остановить процесс PowerShell на удаленном компьютере Server01, введите: For example, to stop the PowerShell process on the Server01 remote computer, type:
Остановка всех остальных сеансов Windows PowerShell Stopping All Other Windows PowerShell Sessions
В некоторых случаях может пригодиться возможность остановки всех выполняющихся сеансов Windows PowerShell, отличных от текущего. It may occasionally be useful to be able to stop all running Windows PowerShell sessions other than the current session. Если сеанс использует слишком много ресурсов или недоступен (он может выполняться удаленно или в другом сеансе), возможно, остановить его напрямую не получится. If a session is using too many resources or is inaccessible (it may be running remotely or in another desktop session), you may not be able to directly stop it. При попытке остановить все выполняющиеся сеансы может быть завершен текущий сеанс. If you try to stop all running sessions, however, the current session may be terminated instead.
Каждый сеанс Windows PowerShell имеет переменную среды PID, содержащую идентификатор процесса Windows PowerShell. Each Windows PowerShell session has an environment variable PID that contains the Id of the Windows PowerShell process. Можно проверить переменную $PID на наличие идентификатора каждого сеанса и завершить только сеансы Windows PowerShell с другим идентификатором. Следующая команда конвейера делает именно это и возвращает список завершенных сеансов (из-за использования параметра PassThru ): You can check the $PID against the Id of each session and terminate only Windows PowerShell sessions that have a different Id. The following pipeline command does this and returns the list of terminated sessions (because of the use of the PassThru parameter):
Запуск, отладка и ожидание процессов Starting, Debugging, and Waiting for Processes
Windows PowerShell также имеет командлеты для запуска (или перезапуска), отладки процесса и ожидания завершения процесса перед выполнением команды. Windows PowerShell also comes with cmdlets to start (or restart), debug a process, and wait for a process to complete before running a command. Дополнительные сведения об этих командлетах см. в разделах справки по каждому из них. For information about these cmdlets, see the cmdlet help topic for each cmdlet.