Page 1 of 1

How to close all CMD windows with PS1 script? [SOLVED]

Posted: 2023-Jul-25, 4:17 pm
by SS##66
Is there way to close all CMD windows [including hidden ones] using strictly PowerShell code?

These two do not work

Code: Select all

Stop-Process -Name cmd.exe -Force

Code: Select all

Stop-Process -Name CMD -Force
even when executed with privileges

Re: How to close all CMD windows with PS1 script?

Posted: 2023-Aug-09, 10:00 am
by SS##66
This

Code: Select all

(Get-Process notepad.Kill()
close both files opened in Notepad and an empty Notepad window opened by executing of

C:\Windows\System32\notepad.exe


But this

Code: Select all

(Get-Process cmd).Kill()
closes only this CMD windows that were opened by going to

C:\Windows\System32\cmd.exe

or

C:\Windows\SysWOW64\cmd.exe

while leaving opened all CMD windows that were evoked by executing of some BAT files; even if PS1 is executed as Administrator

Re: How to close all CMD windows with PS1 script?

Posted: 2023-Aug-09, 10:46 am
by SS##66
The problem all along has been an active countdown in CMD window [used it my test files]- it was making any CMD window with it being immune to being closed with PowerShell

Even as simple BAT as this one

Code: Select all

@echo off
timeout /t 10
pause
will not be closed until the timeout in it is finished, even if PS1 is uses both methods

Code: Select all

Stop-Process -Name cmd -Force
(Get-Process cmd).Kill()
and is executed as Administrator while BAT was without privileges


Solution to this seems to be incorporation of either

Code: Select all

Stop-Process -Name timeout -Force
or

Code: Select all

(Get-Process timeout).Kill()
as apparently CMD window that has an active timeout in changes its name to timeout. This works even if BAT was executed as Administrator while PS1 is not


This is a peculiar behavior, is it not?