Windows завершить процесс удаленно

In Windows, we can kill processes running on a remote computer using the taskkill command. We can specify process id/image file name/user name to identify the processes that need to be killed. Below you can find the syntax for each of the cases with examples.

Kill remote process using process id.

The syntax for this case is as below

Taskkill /S remoteServer /u userName /PID processId

Example:

c:\>taskkill /S 10.132.79.23 /u administrator /PID 5088
Type the password for administrator:******

SUCCESS: The process with PID 5088 has been terminated.

We can as well specify FQDN name of the computer for /S option. We can add /P switch to the above command, to specify the password in the command itself. This will allow the command to be executed from a batch file, without any user interaction.

Kill remote process using image name

We can use filter option (/FI) to specify the image name. The syntax is as given below.

taskkill /s remoteServer  /u userName /FI "IMAGENAME eq filename"

For example, if I need to kill all command window processes, I would run the below command.

taskkill /s 10.132.79.23 /u administrator /FI "IMAGENAME eq CMD.EXE"

If you need to kill outlook process, the command would be:

taskkill /s 10.132.79.23 /u administrator /FI "IMAGENAME eq OUTLOOK.EXE"

Kill processes executed by a particular user

The command is similar to the previous case with one change. Instead of ‘imagename‘, now we use ‘username‘ in the filter argument.

taskkill /s remoteServer  /u userName /FI "USERNAME eq userLoginId"

Viewing the list of processes on remote computer

We can get the remote processes list using tasklist command.
To get list of all the processes, the command is :

tasklist /s remoteServer /u userName

To list the processes running a particular image file:

TASKlist /S remoteServer /u userName /FI "IMAGENAME eq filename"

Example: To get the list of processes running cmd.exe on the remote computer 10.132.79.23, the command is:

c:\>Tasklist /S 10.132.79.23 /u administrator /FI "IMAGENAME eq CMD.EXE"
Type the password for administrator:******

Image Name                     PID Session Name        Session#    Mem Usage
========================= ======== ================ =========== ============
cmd.exe                       4272                            3      2,336 K
cmd.exe                       4448                            3      2,276 K
cmd.exe                       5008                            1      2,392 K
cmd.exe                       4228                            0      2,032 K
cmd.exe                       2344                            0      2,024 K
cmd.exe                       5552                            0      2,028 K
cmd.exe                       2936                            0      2,024 K
cmd.exe                       3776                            1      6,248 K

Perhaps you’re working happily on a remote Windows server, then find a process that runs awry using up valuable CPU cycles. What do you do? Kill it!

In this tutorial, you will learn how to kill a Windows process using native utilities, third-party utilities, and PowerShell. You will first learn how to examine the running processes in Windows and then kill running processes.

Prerequisites

If you’d like to follow along with the steps in this tutorial, be sure you have the following ahead of time:

  • A Windows PC – All demos in this tutorial will use Windows 10, but Windows 7+ will work also.
  • A Windows Server or another Windows desktop to use as your target for killing the remote tasks. This tutorial uses a standalone Windows Server 2016 as the remote server.
  • The Sysinternals Suite from Microsoft.
  • Windows PowerShell 5 or greater. This tutorial uses PowerShell v7.1.3

Querying Remote Windows Process with Tasklist

Since Windows XP, there has been a helpful tool called tasklist. Tasklist is a handy tool that queries processes on remote computers. Before you can kill a process, you must first discover them!

Open a PowerShell session or command prompt on your desktop and type in the following command to display all the running processes on your remote computer.

The command below queries a remote computer (/S) authenticating the connection with the administrator username (/U) and password (/P).

tasklist /S WIN-BANGJIEFNOC.local.net /U administrator /P password

You’ll notice below that the Session Name does not appear. Since you’re running tasklist on a remote computer, tasklist does not provide the Session Name.

list of processes on a remote server

list of processes on a remote server

Perhaps you prefer only to list a single process. Not a problem. To do that, specify the /FI parameter. The /FI parameter accepts a query that is passed to the tasklist to filter out specific processes.

tasklist /S WIN-BANGJIEFNOC.local.net /fi "imagename eq notepad.exe" /U administrator /P 'password'
The output of tasklist showing a specific process

The output of tasklist showing a specific process

Querying Remote Windows Process with PSList

Another tool to view running processes is PSList, and this utility is part of the Sysinternals Suite. This suite of tools has been around for many years and was created by Mark Russinovich, CTO of Azure!

Let’s get started on how you can view running processes on a remote computer.

1. Open a PowerShell session or command prompt on your desktop and change the directory to where you extracted the Sysinternal Suite.

2. In your PowerShell session, run the following command to display the running processes on the remote computer and associated CPU usage in real-time.

The command below runs pslist to query all remote Windows processes on the WIN-BANGJIEFNOC computer authenticating the Administrator username (-u) and password (-p).

The command uses the -s switch turns pslist into “task manager mode” that repeatedly updates the list.

If it’s the first time you have used a Sysinternals tool, a banner may appear that asks you to accept the EULA; click on OK.

.\pslist \\WIN-BANGJIEFNOC.local.net -u Administrator -p 'password' -s

You now see the following output from running that command; for this article, you are concerned with 3 of these values. As shown below.

  • Name: The name of the process.
  • Pid: Process Identifier, a critical value used in this tutorial, the PID number can be used to kill a remote process. It’s the numerical id assigned to a process.
  • CPU: This shows in near real-time the utilization of your overall available CPU.

The other values are memory-related and beyond the scope of this article.

Output in real-time of pslist

Output in real-time of pslist

3. Since step two used the -s switch, hit Ctrl-C to quit pslist to get back to the console.

Narrow down the list of processes returned by using the -e switch followed by the process name, e.g., -e Winlogon.

Killing Processes By Process Name with PSKill

Once you know how to find remote processes, let’s now dive into how to kill them. To start, let’s cover the pskill utility. First, learn how to kill processes by process name.

1. Ensure you have a process you can kill on your remote server. This tutorial will use the notepad process.

2. Open a PowerShell session or command prompt on your local desktop and change the directory to where you extracted the Sysinternal Suite and run the following command. You can see the syntax for pskill is similar to pslist.

.\pskill.Exe \\WIN-BANGJIEFNOC.local.net -u administrator -p 'password' -e notepad.exe
Output of pskill

Output of pskill

3. Now, run pslist, as explained in the previous section, to confirm the process is indeed stopped.

.\pslist \\WIN-BANGJIEFNOC.local.net -u Administrator -p 'password' -e notepad.exe
Output of pslist

Output of pslist

Killing Processes By Process ID with PSKill

Killing the process by name might be good enough for your needs if only a single instance of that process is running or you want to kill all processes with that name. What if you’re going to kill a particular instance of a running process? The following steps will demonstrate this.

1. On your remote server, open Notepad twice; you will kill one of these processes in this demonstration; you can of course, substitute other processes.

2. Run the following command taking note of one of the Pid‘s as shown below; you need that for the next step.

.\pslist \\WIN-BANGJIEFNOC.local.net -u Administrator -p password -e notepad
Using pslist to list PID's of Notepad

Using pslist to list PID’s of Notepad

3. Using the PID, now run pskill, providing the PID as the last argument.

.\pskill.Exe \\WIN-BANGJIEFNOC.local.net -u administrator -p password 1984
The output of pskill for a particular PID

The output of pskill for a particular PID

4. Finally, check that you still have one instance of Notepad running by rerunning pslist. You should now only see a single instance of Notepad running.

Output of pslist

Output of pslist

Killing Remote Windows Processes with TaskKill by Name

The taskkill utility is native to Windows and includes further command-line options for restarting processes by username and application name. Let’s get started and kill Notepad again!

Kill Process by Name

1. On your remote server, open Notepad; Notepad is the process you will kill in this demonstration; you can, of course, substitute another process.

2. Open a PowerShell session or command prompt on your desktop. Typing the following command will kill notepad.exe

taskkill /S WIN-BANGJIEFNOC.local.net /you administrator /p password /IM notepad.exe

The output is shown below:

/IM is the parameter for Image; in this case, it is notepad.exe

The output of taskkill command

The output of taskkill command

3. To confirm the process is stopped, run tasklist. You should now see no tasks are matching that filter.

tasklist /S WIN-BANGJIEFNOC.local.net /fi "imagename eq notepad.exe" /U administrator /P 'password'
Output of tasklist using imagename

Output of tasklist using imagename

Killing Remote Windows Processes with TaskKill by PID

Killing a process with taskkill using a PID isn’t much different than using the process name. But, since you can’t use the name, you’ll first need to find the PID and then pass that to taskkill.

Assuming you Notepad running on your remote Windows host:

1. Run tasklist as shown below to find the PID of the Notepad process. Take note of one of the PID’s as shown below; you need that for the next step.

tasklist /S WIN-BANGJIEFNOC.local.net /fi "imagename eq notepad.exe" /U administrator /P 'password'
the output of tasklist to view PIDS

the output of tasklist to view PIDS

2. Now, run taskkill providing the PID as the last argument.

taskkill /S WIN-BANGJIEFNOC.local.net /u administrator /p 'password' /PID 3776
The output of taskkill specifying a particular PID

The output of taskkill specifying a particular PID

3. Finally, run tasklist to confirm the process is stopped.

Output of tasklist

Output of tasklist

Killing a Remote Windows Process with PowerShell

PowerShell gives you a couple of options for killing remote processes; the first cmdlet Stop-Process cannot natively kill a remote process, as it does not have an option to specify a computer name. But, you can get around this issue by running Stop-Process remotely via PowerShell Remoting.

1. If your host and remote server are not in an Active Directory domain, first provide a username and password, creating a PSCredential object.

$credentials = Get-Credential
Setting up credentials

Setting up credentials

2. Next, since the tutorial will use SSL to connect to the remote computer and use a self-signed certificate, create a PSSessionOption that will skip the certificate check for a trusted certificate authority.

$PSSessionOption = New-PSSessionOption -SkipCACheck

3. Now, connect to the server with the Enter-PSSession command, which establishes an interactive session to the remote server.

The command below is connecting to the WIN-BANGJIEFNOC.local.net computer using the username and password provided above (Credential), skipping the certification authority check (SessionOption), and connecting via SSL (UseSSL).

Enter-PSSession -ComputerName WIN-BANGJIEFNOC.local.net -Credential $credentials -SessionOption $PSSessionOption -UseSSL
Using Enter-PsSession for an interactive session

Using Enter-PsSession for an interactive session

4. Once you’re connected to the remote host, check the process you want to kill by running Get-Process. In this case, you’ll see the notepad process.

Get-Process -ProcessName Notepad
Output of Get-Process

Output of Get-Process

5. To kill this process, run Stop-Process, as shown below.

Stop-Process -ProcessName Notepad

6. Finally, confirm you’ve killed the process by rerunning Get-Process, and you should receive an error message.

Checking for Notepad as a running process

Checking for Notepad as a running process

If you’d like to stop a remote Windows process non-interactively, use the Invoke-Command command using the following parameters: Invoke-Command -ComputerName WIN-BANGJIEFNOC.local.net -Credential $credentials -ScriptBlock {Stop-Process -ProcessName notepad} -UseSSL. Encapsulating the Stop-Proces command in the ScriptBlock parameter sends the command to the remote host.

Conclusion

You have learned about different methods of killing remote processes and how to overcome situations where network firewall rules might stop utilities from working correctly; this tutorial might have also helped you fix Windows.

The utilities you learned about are potent tools; use with care!

Tagged:
PowerShell

Problem

As a system administrator, you may need to kill a process on a remote computer using PowerShell for several reasons, as follows:

  • Troubleshooting: Sometimes, a process can become unresponsive or consume too many resources on a remote computer, causing the system to slow down or even crash. In such cases, killing the process may be necessary to restore the system’s performance and stability.

  • Security: Malware and other malicious software may run in the background without the user’s knowledge, consuming system resources and compromising the system’s security. As a system administrator, you may need to kill these processes to prevent further damage.

  • Maintenance: During system maintenance or upgrades, some processes may need to be stopped to ensure a smooth transition. Killing processes remotely using PowerShell can be an efficient way to manage this process.

In this blog post, we will walk you through how to kill process on remote computer using PowerShell.

Solution

To connect to remote computer, we can create interactive session using Enter-PSSession cmdlet.

In this context, we have two computers named vm1 and vm2 respectively. The client will be vm1 and we want to kill MS Edge processess in vm2.

Since the computers are not in the same domain and we don’t use domain administrator account that typically has privilege to access other computers in the domain, we need to complete some prerequisites. Otherwise, we can jump to how to use Enter-PSSession section.

  1. Enable Windows Remote Management (WinRM) service for both computers

Set-Service -Name WinRM -Status Running -StartupType Automatic

  1. Add servers we want to connect to TrustedHosts list on client computer

Set-Item -Path WSMan:\localhost\Client\TrustedHosts -Value 'vm2'

  1. Enable firewall rule for WinRM to allow other IPs to connect

Set-NetFirewallRule -Name 'WINRM-HTTP-In-TCP' -RemoteAddress Any
Enable-NetFirewallRule -Name 'WINRM-HTTP-In-TCP'

Or you can also do it manually:

1. Open Windows Defender Firewall with Advanced Security
2. Click Inbound Rules
3. Double-click Windows Remote Management (HTTP-In) for the Public profile
4. Click the Scope tab
5. Under Remote IP address, set it to `Any IP Address`
6. Enable Rule
Set-NetFirewallRule -Name 'WINRM-HTTP-In-TCP' -RemoteAddress Any

Enable firewall rule for Windows Remote Management (HTTP-In)

Connect to remote computer using Enter-PSSession cmdlet

To create session to remote computer, we can use Enter-PSSession and specify the computer name we want to connect as well as the credential (username and password).

To close the session, we can use Exit-PSSession cmdlet.


Enter-PSSession vm2 -Credential (Get-Credential)

Stop-Process -Name 'msedge'

Exit-PSSession

connect to remote computer using enter-pssession

stop process on remote computer

Conclusion

To kill process on remote computer, we can create session to remote computer using Enter-PSSession. Then, we can use Stop-Process cmdlet to kill the process. Lastly, to close the session we can use Exit-PSSession cmdlet.

PowerShell предоставляет широкие возможности управления процессами на локальном или удаленном компьютере. С помощью PowerShell можно получить список запущенных процессов, приостановить зависший процесс, найти процесс по заголовку окна, запустить новый процесс в скрытом или интерактивном режиме.

Список доступных командлетов управления процессами в Windows 10 можно вывести так:

Get-Command –Noun Process

командлеты управления процессами в powershell

  • Get-Process – получить список запущенных процессов;
  • Start-Process – запустить процесс/программу;
  • Stop-Process – принудительно остановить процесс;
  • Debug-Process – используется для отладки процессов;
  • Wait-Process – используется для ожидания окончания процесса.

Содержание:

  • Get-Process – получение списка запущенных процессов
  • Start-Process, Stop-Process: запуск и остановка процессов из PowerShell
  • PowerShell: управление процессами на удаленном компьютере

Get-Process – получение списка запущенных процессов

Командлет
Get-Process
позволяет вывести список запущенных процессов на локальном компьютере.

Get-Process список запушенных процессов

По-умолчанию выводятся следующие свойства запущенных процессов:

  • Handles – количество дескрипторов ввода — вывода, которые отрыл данный процесс;
  • NPM(K) — Non-paged memory (невыгружаемый пул). Размер данных процесса (в Кб.), которые никогда не попадают в файл подкачки на диск;
  • PM(K) – размер памяти процесса, которая может быть выгружена на диск;
  • WS(K) – размер физической памяти в Кб, используемой процессом (working set).
  • CPU(s) – процессорное время, использованное процессом (учитывается время на всех CPU);
  • ID — идентификатор процесса;
  • SI (Session ID) – идентификатор сеанса процесса (0 — запущен для всех сессий, 1 – для первого залогиненого пользователя, 2 — для второго и т.д.);
  • ProcessName – имя процесса.

Чтобы получить все свойства нескольких процессов:

Get-Process winword, notep* | Format-List *

Можно вывести только определенный свойства процессов. Например, имя (ProcessName) время запуска (StartTime), заголовок окна процесса (MainWindowTitle), имя исполняемого файла (Path) и наименование разработчика (Company):

Get-Process winword, notep* | Select-Object ProcessName, StartTime, MainWindowTitle, Path, Company|ft

вывести подроюную информацию о запущенных процессах

Вывести список запущенных процессов пользователя с графическими окнами (в список не попадут фоновые и системные процессы):

Get-Process | Where-Object {$_.mainWindowTitle} | Format-Table Id, Name, mainWindowtitle

Get-Process | Where-Object {$_.mainWindowTitle - процессы с графическими окнами

С помощью параметра
IncludeUserName
можно вывести имя пользователя (владельца), который запустил процесс:

Get-Process -Name winword -IncludeUserName

С помощью Where-Object можно выбрать процессы в соответствии с заданными критериями. Например, выведем все процессы, которые используются более 200 Мб оперативной памяти, отсортируем процессы в порядке убывания используемого объема RAM, размер памяти из Кб преобразуем в Мб:

Get-Process| where-object {$_.WorkingSet -GT 200000*1024}|select processname,@{l="Used RAM(MB)"; e={$_.workingset / 1mb}} |sort "Used RAM(MB)" –Descending

Get-Process найти процессы, которые занимают более 200 Мб оперативной памяти

Как мы уже говорили ранее командлет Get-Process в параметре CPU содержит время использования процессора конкретным процессом в секундах. Чтобы отобразить процент использования CPU процессами (по аналогии с Task Manager), используйте такую функцию:

function Get-CPUPercent
{
$CPUPercent = @{
Name = 'CPUPercent'
Expression = {
$TotalSec = (New-TimeSpan -Start $_.StartTime).TotalSeconds
[Math]::Round( ($_.CPU * 100 / $TotalSec), 2)
}
}
Get-Process | Select-Object -Property Name, $CPUPercent, Description | Sort-Object -Property CPUPercent -Descending | Select-Object -First 20
}

Get-CPUPercent

Чтобы найти зависшие процессы (которые не отвечают), выполните команду:

Get-Process | where-object {$_.Responding -eq $false}

Start-Process, Stop-Process: запуск и остановка процессов из PowerShell

Чтобы запустить новый процесс с помощью PowerShell используется команда:

Start-Process -FilePath notepad

Если каталог с исполняемым файлом отсутствует в переменной окружения $env:path, нужно указать полный путь к файлу:

Start-Process -FilePath 'C:\distr\app.exe'

Можно запустить программу и передать ей аргументы:

Start-Process -FilePath ping -ArgumentList "-n 10 192.168.1.11"

С помощью параметра WindowStyle вы можете задать режим запуска окна процесса (normal, minimized, maximized, hidden). Например, чтобы запустить программу в максимально развернуом окне и дождаться завершения процесса, выполните команду:

Start-Process -FilePath tracert -ArgumentList "192.168.1.11" –wait -windowstyle Maximized

С помощью командлета Stop-Process можно завершить любой процесс. Например, чтобы закрыть все запущенные процессы notepad:

Stop-Process -Name notepad

По-умолчанию не запрашивается подтверждение завершения процесса. Закрываются все процессы, которые соответствуют указанным критериям. Чтобы запросить подтверждение завершения для каждого процесса, добавьте –Confirm.

Stop-Process -Name notepad.exe -Confirm

Stop-Process завершить процесс powershell

Также завершить процесс можно так:

(Get-Process -Name notepad).Kill()

Из PowerShell можно принудительно завершить все приложения, которые не отвечают диспетчеру процессов Windows:

Get-Process | where-object {$_.Responding -eq $false}| Stop-Process

PowerShell: управление процессами на удаленном компьютере

С помощью аргумента ComputerName командлет Get-Process позволяет управлять процессами на удаленных компьютерах (должен быть включен и настроен WinRM).

Get-Process -ComputerName dc01, dc02| Format-Table -Property ProcessName, ID, MachineName

Мы рассматриваем встроенные возможности комнадлета Get-Process для управления процессами на удаленных компьютерах. Здесь не учитываются возможности PowerShell Remoting, которые доступны в командлетах Invoke-Command и Enter-PSSession.

Если вы хотите завершить процесс на удаленном компьютере, имейте в виду, что у командлета Stop-Process отсутствует параметр –ComputerName. Для завершения процесса на удаленном компьютере можно использовать такой PowerShell код:

$RProc = Get-Process -Name notepad -ComputerName dc01
Stop-Process -InputObject $RProc

powershell:remote-windows-management:how-to-remotely-get-and-close-kill-a-process-in-powershell

Как удалённо получить и/или закрыть процесс в PowerShell

Пример того, как на клиентской машине с помощью PowerShell и WMI получить информацию о всех выполняемых процессах на удалённом сервере:

Get-WmiObject win32_process -ComputerName "KOM-SRV01" | `
select -Property ProcessName,ProcessId,ParentProcessId,Path | sort ProcessId | ft

Пример того, как удалённо закрыть процесс, зная его идентификатор PID.

Например, закроем процесс с PID 5660:

Get-WmiObject Win32_Process -Filter "ProcessId LIKE '5660'" -ComputerName "KOM-SRV01" | `
Invoke-WmiMethod -Name Terminate

Пример того, как удалённо закрыть процесс по маске его исполняемого файла.

Например, закроем все процессы с испоняемым файлом notepad.exe:

Get-WmiObject Win32_Process -Filter "ExecutablePath LIKE '%notepad.exe%'" `
 -ComputerName "KOM-SRV01" | Invoke-WmiMethod -Name Terminate

Проверено на следующих конфигурациях:

Версия ОС / PowerShell (сервер) Версия ОС / PowerShell (клиент)
Windows Server 2012 R2 Standard / PowerShell 4.0 Windows 10 1803 (10.0.17134) / PowerShell 5.1

Автор первичной редакции:
Алексей Максимов
Время публикации: 28.05.2018 18:44

Понравилась статья? Поделить с друзьями:
0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии
  • Как убрать группы в проводнике windows 10
  • Windows server 2016 не удается активировать
  • Компьютер не видит устройство вывода звука windows 10
  • Как очистить файлы обновлений windows 10
  • Как удалить ssh key windows