Managing processes in complex Windows environments can be an overwhelming and time-consuming experience. Having to be constantly logging into different machines at different times, hitting the “Ctrl+Alt+Del”, looking for specific processes, and “Ending Tasks” is a long and tedious process.
With PowerShell (PS), you can programmatically find and stop a service. You can use PS’s cmdlets to create scripts to look for and stop a specific service, scripts that kill a process based on specific criteria, auto-startup scripts, or whatever sets your imagination.
In this tutorial, you’ll learn how to locate and kill any process using two different commands available in PowerShell, the TASKKILL and the Stop-Process cmdlet. The advantage of using PowerShell over simple CMD, is that you can create automation routines to close processes.
Table of Contents
- Kill a process using PowerShell
- Why would you want to kill a process?
- Install and Open PowerShell.
- Open the PowerShell Interface.
- Killing a process with TASKKILL
- How to use TASKKILL?
- Forceful (/f) vs Graceful?
- Task Listing.
- Using TASKKILL in PowerShell?
- Killing a Process with PowerShell’s Stop-Process
- TASKKILL vs Stop-Process?
- A Stop-Process Example?
- Conclusion
Kill a Process Using PowerShell
When an application (or service) starts, Windows OS creates a process for the executable file. This process contains the code and the current activity. Additionally, the OS also creates a unique Process Identifier (PID) for that particular process. This PID is a decimal number that can be used for debugging or troubleshooting.
An example is when you open an application such as Chrome or Skype, Windows creates a particular PID for each of those applications. You can use this PID to attach a debugger, monitor it, or kill the process.
Why would you want to kill a process?
The two traditional ways to kill a process are via the Windows Task Manager and the CMD command prompt. The third way, not so common but very efficient, is using PowerShell.
Install and Open PowerShell
PowerShell (PS) is Microsoft’s automation and configuration management framework. It comes with its own command-line shell and scripting language. PS works well with any tool and is optimized to work with structured data (CSV, XML, JSON, etc), and REST APIs.
Microsoft’s PS is open-source and available as a cross-platform. It is available on Windows, Linux, or macOS.
To download, install, or update the latest stable version of PowerShell, visit the GitHub repository: https://github.com/PowerShell/PowerShell/
Now, let’s open the PowerShell Interface.
Press “Windows + R” keys to open the run box, and type “PowerShell”. Clicking “Ok” will open a regular PS interface. But you can also open an interface with elevated permissions, by pressing Ctrl+Shift+Enter.
Although the PS interface looks a lot like Windows Command Prompt (cmd), PS is a more advanced “version” of cmd. As mentioned before PS comes with its own scripting language and command-line shell.
With PowerShell, you can run any cmd command, like ListTask or KillTask.
Killing a process with TASKKILL
Let’s start by defining the TASKKILL utility (taskkill.exe) and how to use it.
TASKKILL is a Microsoft utility that allows you to terminate one or more processes (or tasks). At the basic level, TASKKILL is like clicking the X button on the top-right corner of any Windows application. It will “gracefully” exit the program and will prompt you “whether to save changes” before exiting. However, the TASKKILL utility gives you more flexibility on how you would want to kill a process— you can go gracefully or forcefully.
This utility can be used from the command line with different configuration arguments such as /F, /T, PID, and /IM.
The TASKKILL command syntax is (As shown in the screenshot above):
The useful parameters to kill a process with TASKKILL are:
- /S (System) Define the remote system to connect to.
- /U (Username) Specify the username.
- /P (password) Determines the password for that specific user.
- /PID (Process ID) Specify the ID of the process you want to terminate.
- /IM (Image name) Specify the image name of the process you want to terminate.
- /T (Terminate) Terminate the PID along with any child processes associated with it.
- /F (Forceful) Forcefully terminate the process.
How to use TASKKILL?
Let’s put together a couple of TASKKILL parameters.
taskkill /PID process-number /F
taskkill /IM process-name /F
Forceful (/f) vs Graceful?
As many of us have probably experienced before, the graceful way to exit a program (the “X” on top of a Windows bar) will usually not work, if an application is frozen or buggy.
When you force a process to exit (forceful kill), you are doing the same as Alt+F4 or going to the task manager with Ctrl+Alt+Del and clicking on “End Task”. Without the parameter (/F) is like clicking on the (X) on the top bar of any window.
So, you’ll need to force a program to exit with (/f) in some cases.
Task Listing
You can also filter your search based on some criteria using the “/fi” parameter. For example:
tasklist /fi "imagename eq notepad.exe"
Again, if you want to know more about the Tasklist command, type “tasklist/?” on the command prompt.
Using TASKKILL in PowerShell?
First, as mentioned before, use the TASKLIST command to find the Image Name and its PID:
Find the name of the process and record the PID or image name (i.e., notepad.exe).
In this example, “notepad.exe” is using the PID:13252
- To gracefully kill the notepad process with pid:
taskkill /pid 13252
- To forcefully kill the notepad process with pid:
taskkill /pid 13252 /f
- To forcefully kill the notepad process using image name:
taskkill /im notepad.exe /f
Kill a Process with PowerShell’s Stop-Process
The Stop-Process is PowerShell’s own way to kill a process (although they prefer to use the word “Stop” rather than killing!). Stop-Process is a cmdlet that performs similar to the TASKKILL command but gives you a slightly different set of options.
The Syntax for the Stop-Process command is as follows:
- Stop-Process [-id] <Int32[]> [-passThru] [-Force] [WhatIf][-confirm] [<CommonParameters>]
- Stop-Process -name string[] [-passThru] [-Force] [-WhatIf] [-confirm] [<CommonParameters>]
- Stop-Process -inputObject Process[] [-passThru] [-WhatIf] [-Force] [-confirm] [<CommonParameters>]
TASKKILL vs Stop-Process?
PowerShell’s Stop-Process, on the other hand, helps you create an autonomous task with scripting powers. For example, the “-passthru” parameter allows you to return objects from commands, which you can later use for scripting. The Stop-Process also includes two risk mitigation parameters (-WhatIf) and (-Confirm) to avoid the Stop-Process from making dramatic changes to the system.
A Stop-Process Example?
We’ll kill the notepad process forcefully, first by defining its PID, and then by its process name.
Step 1. Find it
Use the “Tasklist” command to see all your processes (or create a filter).
Step 2. Stop the process with its PID:
Optional: You can also stop the process using its name. For example:
- Stop-process -name notepad -Force
- Stop-Process -name CMD -Force
- Stop-process -name putty -Force
- Stop-Process -Name Chrome -Force
To return a process object to the PowerShell console, use the PassThru command. This command is useful for keeping track of process objects. For example, if you want to monitor the newly opened Notepad process.
The below screenshot starts the process with a -PassThru parameter and later stops the same process with a -PassThru. You can store the returned process object into a variable and use it to monitor metrics like CPU or PM, etc.
Conclusion
Buggy or problematic services and applications can be overwhelming. They are time-consuming to manage and can make entire servers slow— or even crash them.
Instead of having to every time restart the entire server, you can kill the specific service that is giving you headaches, and get the server back to normal.
In this tutorial, we went through two ways to kill a process using PowerShell. The TASKKILL is simple and easy to use. You can connect to remote servers and kill processes using its PID or name. The PowerShell’s Stop-Process cmdlet can do the same but goes beyond by allowing you to automate tasks. With Stop-Process, you can create auto-restart scripts that monitor and kill risky processes.
PowerShell Kill Process Command FAQs
Can I use TASKKILL to terminate multiple processes at once?
How can I find the process ID of a process?
You can use the Task Manager to find the process ID of a process. In Task Manager, select the “View” menu, then select “Select Columns,” and then check the “PID (Process Identifier)” check box. Or you can use the command line tool tasklist in the command prompt, which will list the running process with their pid.
What happens when I use the TASKKILL command?
When you use the TASKKILL command, the specified process is terminated and all resources associated with it are freed up.
Can I use TASKKILL to terminate a process that is not responding?
Yes, you can use the /F option with the TASKKILL command to force the termination of a process that is not responding.
Oracle, SQL Server, PostgreSQL
Процессы ОС Windows и соответствующие проблемы
В этой статье мы расскажем о проблемах, сопутствующих ОС Windows, и средствах диагностики этих неполадок, которые используют специалисты «ДБ-сервис».
Основные процессы ОС Windows
В актуальных версиях Windows процессы принято делить на три группы:
- Процессы приложений. Процессы прикладных программ, как встроенных в ОС, так и внешних.
- Фоновые процессы. Процессы, не имеющие собственных окон и протекающие непрерывно. Среди них могут быть и запущенные ОС (службы), процессы внешних программ (антивирусы, сборщики аналитики и т.д.)
- Процессы Windows. Процессы операционной системы, отвечающие за ее функционирование.
Из-за чего возникают проблемы ОС Windows?
Существует много причин возникновения неполадок в ОС Windows. В контексте процессов, влияющих на работу СУБД, в качестве проблемы мы рассмотрим аномальное число всех процессов, а также чрезмерное количество работающих скриптов PS или командной строки.
Слишком много процессов
В норме число процессов в Windows не должно превышать 100. Если это значение достигает 1000, это может говорить о наличии неполадок или каких-то серьезных изменениях в системе. В этом случае необходимо проверить, что это за процессы.
Ниже мы подробно опишем инструменты диагностики, которые мы используем в «ДБ-сервис»; пока же отметим лишь, что т. к. процессы, выполняющиеся на машинах клиентов могут быть очень важны для их бизнеса, мы ничего не останавливаем без подтверждения от заказчиков.
Количество запущенных процессов (conhost.exe) или (powershell.exe) слишком велико
Нередки ситуации, когда источником проблемы является большое число скриптов, работающих одновременно и выполняющих разные задачи (речь идет о процессе командной строки conhost.exe или процессе powershell.exe).
Причина, как правило, кроется в том, что скрипты стали выполняться слишком долго, в силу чего висят запущенными в памяти, наслаиваясь друг на друга.
В свою очередь долгое выполнение скриптов происходит из-за неполадок на сервере или ошибок в БД, если скрипты обращаются к ней (к примеру, в случае блокировок, о которых мы писали в одной из предыдущих статей).
Первое, что необходимо сделать в этом случае — идентифицировать источник проблем. Далее необходимо проверить сервер и БД на предмет общей деградации производительности.
В случае невозможности самостоятельного проведения диагностики — следует передать данные специалистам по поддержке и администрированию баз данных, например — инженерам «ДБ-сервис». Помните, что ответ на вопрос «как запустить процесс Windows и ничего не сломать» — не всегда является тривиальным.
Как диагностировать проблему?
Существует несчетное число инструментов для диагностики проблем с процессами ОС. В этой статье мы не будем рассматривать сторонние утилиты, а сосредоточимся на только стандартных средствах Windows.
Диспетчер задач Windows (Task Manager)
Диспетчер задач — стандартный графический инструмент управления процессами. Они отображаются и управляются в двух вкладках — «Processes» и «Details» — внешний вид которых может варьироваться в зависимости от версии Windows.
1. Вкладка «Processes». Как видно на скрине ниже, в ней содержится основная информация о процессах и показатели производительности.
В этом окне диспетчера можно группировать, сортировать, добавлять и удалять отображаемую информацию, что помогает эффективнее анализировать производительность.
2. Вкладка «Details». Как видно из скрина ниже, в этой вкладке содержится более подробная информация о процессах.
Командная строка в Windows — это программа, которая эмулирует поле ввода в пользовательском интерфейсе. Для управления процессами в командной строке есть две утилиты:
- Tasklist. Показывает список процессов на локальном или удаленном компьютере. Для каждого процесса выводит имя образа, PID, имя сессии, номер сеанса и объем занимаемой памяти.
- Tasklist. Помогает завершить любой процесс.
Например, команда Tasklist /v /fo LIST выведет подробное описание всех процессов в виде списка.
Полную справку по командам Tasklist и Taskkill можно получить, введя их с ключом /?.
Еще один важный инструмент диагностики — PowerShell. Речь идет о конгломерате командлетов, с помощью можно управлять процессами на локальном или удаленном компьютере.
Для получения списка процессов используется командлет Get-Process. Пример вывода результатов можно увидеть на скриншоте ниже.
Частые ошибки при диагностировании проблем
При диагностировании проблем, связанных с процессами Windows, у людей, далеких от системного администрирования, часто возникают те или иные затруднения. Поэтому, чтобы не подставлять бесперебойность вашего бизнеса под удар, мы советуем доверять диагностику профессионалам. Обратившись в «ДБ-сервис», вы получите экспертное сопровождения ваших БД, а также
весь комплекс работ по их администрированию в режиме 24×7
Мы рассказали об основных типах процессах в ОС Windows и неполадках, возникающих из-за их аномальной работы. Также в статье было освещено, как «ДБ-сервис» использует для диагностики проблем инструменты, встроенные в оболочку Windows.
Опыт работы: 9 лет администрирования СУБД MSSQL SERVER
Образование: ЮФУ, Диплом специалиста по специальности «Физика», Диплом магистра по специальности «Прикладная информатика», Диплом о профессиональной переподготовке по специальности «Системный инженер»
Пономаренко Георгий Олегович
Руководитель направления MSSQL
This tutorial will guide you through the process of identifying and terminating processes using PowerShell. You will learn how to open and navigate the PowerShell environment, get a list of running processes, and use commands like ‘Taskkill’ and ‘Stop-Process’ to terminate processes by their ID or name. We will also briefly discuss how to kill a process without PowerShell using the Task Manager.
Networking and Cyber Security Specialist
Updated: November 30, 2023
Related post: 25 Essential PowerShell Commands
Windows assigns a Process ID (PID) to each process that it starts up. So you need to identify the PID for the task you want to terminate.
The steps are:
Open the PowerShell environment
2. Windows will ask you for your permission to proceed. Click OK and the PowerShell app will open. This shows a blue background and has the PowerShell prompt at the top of it. The prompt also shows the current directory which defaults to C:\Windows\system32.
3. If you want to run your own scripts from this prompt, you can change the directory with the command cd <directory>
(substitute the directory name you want to move to for <directory>).
Get a list of running processes
All the methods available to kill a process require a PID as a parameter. The list of running processes can be long but you can move up and down the screen by using the slider bar to the right of the PowerShell Window.
The PID is the second column in the output. The first column lists the names of the processes. You will notice that a lot of the processes are called svchost.exe. This is not very helpful because if you want to stop one of these processes, it is impossible to work out which is the one that is giving you trouble.
Once you have identified the process you want to terminate, you have two options to kill it: taskkill and stop-process.
Note that all methods to kill a process require a PID
Kill a process with Taskkill
Taskkill allows you to kill a process either by its PID or by the name listed for it in the tasklist output.
To stop a process by its ID, use taskkill /F /PID <PID>
, such as taskkill /F /ID 312
7 if 3127 is the PID of the process that you want to kill.
To stop a process by its name, use taskkill /IM <process-name> /F
, for example taskkill /IM mspaint.exe /F
.
Kill a process with Stop-Process
Like Taskkill, Stop-Process lets you use either the PID or process name to kill a process. The name needs to be as shown in the tasklist output.
To stop a process by its ID, use the format: Stop-Process -ID <PID> -Force
, eg. Stop-Process -ID 3127 -Force
.
To stop a process by its name, use the format: Stop-Process -Name <process-name> -Force
, eg. Stop-Process -Name mspaint.exe -Force
.
Kill a process without PowerShell
If you just want to kill a process and you aren’t interested in using a command that you can put in a script, the easiest method is through the Task Manager, which is part of Windows.
- To get Task Manager, right-click on a vacant space on the taskbar and select Task Manager from the context menu.
- In Task Manager, scroll through the list of running processes that are shown in the Process tab of the interface.
- Click on the process that you want to stop and then click on the End task button at the bottom-right of the interface.
Using Software
SolarWinds Server & Application Monitor
Take a look at the SolarWinds Server & Application Monitor. This tool includes process management. This has a screen that shows all running processes and also includes a kill button. This utility can be set to look for specific conditions, such as a process that runs longer than a given time or one that seems to be inactive. Under these circumstances, you can set the system to send you an alert, so you don’t have to sit looking at the screen all day in order to keep track of problematic processes. SolarWinds offers the Server & Application Monitor on a 30-day free trial.
SolarWinds Server & Application Monitor
Get a 30-day FREE Trial
How do I stop a PowerShell command from running?
You can interrupt and stop a PowerShell command while it is running by pressing Control-C. A script can be stopped with the command exit. This will also close the PowerShell console.
How do I kill Windows processes from the command line?
At the command line, you can terminate a Windows process with the command taskkill. To use this command, you need to know its process ID (PID). You can get a list of all running tasks with the command tasklist. Once you know the PID, use the taskkill command in this manner: taskkill /PID <PID> /F. Type in the process ID without quotes instead of <PID>.
PowerShell offers a way to manage processes programmatically with scripts. However, it can be time-consuming, and numerous pre-existing tools may perform process management more efficiently than a simple script you create.
I am working on a powershell script that looks for a defined process in order to stop it (and restart it, if it was running before) in order to perform an update of that software.
We use the Microsoft System Center Configuration Manager
to perform that task.
Here is a snippet that we use for debugging:
$fileName = "MyFile.exe"
$processes = Get-Process
foreach ($process in $processes) {
# Process found?
if ($process.MainModule.FileName -like "*\$fileName") {
Write-Host "Process found" -ForegroundColor Green
}
else{
Write-Host "Not the right process" $process.MainModule.FileName -ForegroundColor Red
}
}
asked Dec 13, 2023 at 13:53
$taskListOutput = & tasklist /fo csv /FI "imagename eq $fileName"
$splitTaskListOutput = $taskListOutput -split "`r`n"
if($splitTaskListOutput.Count -gt 1)
{
Write-Host "Process found"
try {
$columns = $splitTaskListOutput[1].Trim('"') -split '","'
# Stop by process ID
Stop-Process -Id $columns[1]
Write-Host "Process terminated"
} catch {
return -1 # Process could not be terminated
}
}
The actual reason why the process can not be found in powershell by SCCM remains a mystery.
answered Dec 21, 2023 at 12:32
1 gold badge15 silver badges31 bronze badges
In this guide, you will learn how to list all Scheduled Tasks using PowerShell.
I will walk you through several examples for local and remote computers, and also show you how to filter the task list.
Table of Contents:
The Get-ScheduledTask Command (Syntax)
The Get-ScheduledTasks command is used to get the registered tasks on a local computer. By using the command parameters you can also get a list from remote computers.
To view the command syntax use the below command.
get-command -Module get-scheduledtasks

List Scheduled Tasks on Local Computer
To list the scheduled tasks on your local command run the command below.
Get-ScheduledTask

Here are some commands to filter the list of scheduled tasks.
List all Active Scheduled Tasks
Use this command to display only the active scheduled tasks.
get-scheduledtask | where state -eq 'Ready'

List all Disabled Scheduled Tasks
To display all the disabled scheduled tasks use this command.
get-scheduledtask | where state -eq 'Disabled'
List Scheduled Tasks Using Wildcard Search
If you don’t know the name of a scheduled task you can use a wildcard search. In this example, I’ll list any scheduled tasks that have “Firefox” in the taskname.
get-scheduledtask -taskname 'windows*'

Here is one more wildcard example. In this example, I want to list all of the Microsoft Office scheduled tasks. I’ll search for any taskname that has Office in the name.
get-scheduledtask -taskname 'Office*'

List Scheduled Tasks on Remote Computer
To get a list of scheduled tasks on a remote computer, you can use the -CimSession parameter. You will need PowerShell Remoting enabled for this to work.
In this example, I’m working on DC1 and will get the scheduled tasks on remote computer PC1.
Get-ScheduledTask -CimSession PC1

In this example, I’ll use the Service Accounts Report Tool to list all scheduled tasks on a group of computers. This is an easy-to-use graphical tool that can also list Windows services.
This GUI tool solves that problem by displaying additional details like Running As, Last Run Results, and Last Run time.
This is useful to help track down Active Directory accounts that are running scheduled tasks or Windows services on remote computers. These accounts can become a security risk and cause random account lockouts.
Step 1: Select Computers
Download a Free Trial
Select to scan all computers, an OU/group, or search the domain for specific computers.

Step 2: Click Run
Click the “Run” button and the tool will scan the selected computers for Scheduled tasks and Windows services.

When the report is completed you can click on any column to easily filter and sort the results. In this example, I’ve filtered for any task and service running as “robert.allen”.

I found that my Active Directory account is being used to run a Scheduled Task on server “SRV-VM1”.
You can filter and sort on any column. In the screenshot below I’ve filtered for all tasks and services that are running.

In this guide, I showed you how to use PowerShell to list the scheduled tasks on local and remote computers. Although the Get-ScheduledTasks is easy to use, it may not provide all the details you need when scanning remote computers.
If you want to know what is happening on your Windows computer, you may want to check the running apps and processes. These are the programs and services that are using your system resources, such as CPU, memory, disk, and network. By checking the running apps and processes, you can monitor the performance of your computer, identify and troubleshoot any issues, and optimize your system for better speed and efficiency.
There are different ways to check the running apps and processes on your Windows. Please read on as we will show you three of them: using the Task Manager, using the “tasklist” command, and using Wise Care 365 in this article.
Method 1 Task Manager
You can easily check which apps are running on your Windows 11 using the Task Manager.
Step 1. Open Task Manager
Press Ctrl + Shift + Esc or Ctrl + Alt + Del and then select Task Manager to open the app.
Step 2. View all running apps
Then switch to the Processes tab to see the apps and processes running in the background.
Method 2 The “tasklist” Command
Besides that, you can use the “tasklist” command in Command Prompt or Windows PowerShell to list all running apps and background processes in Windows 11.
CMD
The Command Prompt is a Windows built-in tool that allows you to execute commands and perform various tasks on your computer.
- Click on the Start button and type “Command Prompt”. Then, right-click on the Command Prompt app and select Run as administrator;
Alternatively, you can press Windows key + R on your keyboard, type “cmd”, and press the Enter key.
- In the Administrator: Command Prompt window, type “tasklist” and press Enter.
- As you enter the above command, you will see a list of all the running apps and processes on your computer, along with their Names, PIDs, Session names, Session numbers, and Memory usage.
PowerShell
Windows PowerShell is another built-in tool that allows you to execute commands and scripts and perform various tasks on your computer.
- Press Windows key + X on your keyboard and select Terminal (Admin) from the menu.
- Now, to identify running programs on your PC, you can type “tasklist” and press Enter.
- It will list down every running process in the window.
Method 3 Wise Care 365
In addition to these, you can use Wise Care 365 to check and manage all running apps and background processes easily on almost all Windows versions from Windows XP and up.
Wise Care 365 is PC performance optimization software designed for Windows operating systems. It includes a range of tools to enhance the performance, clean up disk space, and provide system maintenance of Windows PCs.
Step 2. Select System Monitor
Launch Wise Care 365 and click on the System Monitor icon on its main interface.
Step 3. Click Process Monitor
Click on the Process Monitor tab on the left panel. You will see a list of all the running processes on your computer, along with their Names, Locations, CPU usage, Memory usage, and so on. You can sort the list by any of these criteria by clicking on the column headers.
Step 4. Check the details
To check the details of a specific process, you can move your mouse pointer to the process and click on the drop-down arrow of it, then select Detailed Info to open its Properties.
Step 5. Manage a process
To manage a specific process, you can click on End Process in its drop-down menu to terminate the process and free up the resources it occupies.
Conclusion
In this article, we have shown you three ways to check the running apps and processes on your Windows PC. Each of these tools has its own advantages and disadvantages, and you can choose the one that suits your needs and preferences.
By using the free feature System Monitor in Wise Care 365 , you can easily check all the running apps on Windows and manage them accordingly. You can also use other features of Wise Care 365 to clean, optimize, and protect your Windows computer.

In my last post, I wrote about wanting to run my web projects and tests in one terminal window and how I achieved it using DotnetBackground.
How does this compare to
start dotnet run
in Command Prompt, andstart-process -FilePath dotnet -ArgumentList 'run'
in PowerShell?
Let’s see if we can use these commands to also accomplish our goals of running the web apps and tests in one terminal window.
DotnetBackground
Let’s recap with what we ended up having to do in DotnetBackground. This is what I had to do to start the dotnet run
as a background process:
DotnetBackground run .NimblePizza.BlazorNimblePizza.Blazor.csproj --launch-profile https
Then, I could run dotnet test
.
Finally, I could stop the background processes with:
start
Command in the Command Prompt
The first command Peter asked about is the start
command in the Command Prompt. Initially, I tried start dotnet run
with my parameters from above, but it opened in another terminal window. Time to look at the start
documentation.
In theory, I can use /b
to run this as a background process.
Let’s try this:
start /b dotnet run .NimblePizza.BlazorNimblePizza.Blazor.csproj --launch-profile https
Since we don’t know the process ID, we can use taskkill
with the executable name to kill the process.
If it fails to terminate, there may be a good reason for it. The error messages tend to be descriptive in what went wrong. When I ran this the first time, it told me that the process needed to be stopped forcefully (with /F option). So I ended up running this:
taskkill /IM dotnet.exe /F
Now what if you wanted to find the process ID? Use tasklist
to see all current tasks. You can use /M
and do a wildcard search of what’s running. So I found my process ID (PID) using:
Start-Process
in PowerShell
The other part of Peter’s question was around start-process -FilePath dotnet -ArgumentList 'run'
. Let’s see how we can accomplish this in PowerShell!
Note: PowerShell has an alias of
start
for theStart-Process
cmdlet. This alias is not the same as thestart
command I mentioned earlier.
So in theory, I should be able to run this command in PowerShell:
FilePath dotnet ArgumentList "run --project .\NimblePizza.Blazor\NimblePizza.Blazor.csproj --launch-profile https"
However, this starts another terminal window. Let’s consult the Start-Process documentation. That -NoNewWindow
looks promising. Try this:
NoNewWindow FilePath dotnet ArgumentList "run --project .\NimblePizza.Blazor\NimblePizza.Blazor.csproj --launch-profile https"
Once you’re done with those dotnet processes, you can stop them with this command:
Name dotnet
Conclusion
Thanks, Peter Ritchie, for the question!