How to Kill Process searching for Description with Loop via Powershell - windows

I'm trying to figure out how to create a batch file by searching a text on Description of the Process then killing it. I managed to find one on this stackoverflow. But how do I loop this search before killing it?
This is the batch file I made
:loop
powershell -command "(get-process | ? {$_.Description -like 'Internet*'} if $_.Description -ne "Internet*" ( GOTO LOOP) ELSE (get-process | ? {$_.Description -like 'Internet*'}).kill())"
Well I'm just trying to experiment it but it's not working. I have a super little knowledge about Powershell.
FYI: I'm doing this because I own a Computer shop and there are some people who are trying to use the Internet Download Manager Portable to download big files, I tried limiting the bandwidth of the idman.exe using NetLimiter, but they are just renaming the file to let say 1.exe or 2.exe etc., so that's why I will try using the task scheduler and run this batch file in the background.

I'm not sure killing the process would be a good solution in your case, but if you trying to kill a process with a specific description, you can simply pipe the process to Stop-Process.
Get-Process | where {$_.Description -like "Internet*"} | Stop-Process

Related

Launch Applications in WIndows using AppID and get the pid

I'm trying to launch Windows applications using their AppID such as Microsoft.WindowsCalculator_8wekyb3d8bbwe!App which I get by calling Get-StartApps
Currently I can launch the applications but can't get the correct PID
cmd = exec.Command("powershell", "start", `shell:AppsFolder\Microsoft.WindowsCalculator_8wekyb3d8bbwe!App`)
err := cmd.Start()
fmt.Println(cmd.Process.Pid)
This returns the PID of powershell
C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe start shell:AppsFolder\Microsoft.WindowsCalculator_8wekyb3d8bbwe!App
Is there a way to launch the application by the AppID and still get the correct PID?
tl;dr
// Make PowerShell not only launch Calculator, but also
// determine and output its PID, as described in the next section.
out, _ :=
exec.Command(
`powershell.exe`,
`-NoProfile`,
`-Command`,
`Start-Process -ErrorAction Stop calculator: ; (Get-Process Calculator | Where-Object SessionId -eq (Get-Process -ID $PID).SessionId).ID`,
).Output()
// Parse stdout output, which contains the PID, into an int
var pid int
fmt.Sscanf(string(out), "%d\n", &pid)
In principle, you can pass -PassThru to PowerShell's Start-Process (start) cmd, which returns a process-info object that has an .Id property containing the launched process' PID, and output the latter.
Unfortunately, with UWP / AppX applications specifically, such as Calculator, this does not work, which is a problem that exists in the underlying .NET APIs, up to at least .NET 6.0 - see GitHub issue #10996.
You can try the following workaround:
Launch the AppX application with Start-Process, which indirectly creates a process whose name is Calculator (Windows 10) / CalculatorApp (Windows 11).
You can identify this name yourself if you run (Get-Process *calc*).Name after launching Calculator. Get-Process *calc* | Select-Object Name, Path would show the executable path too, but note that this executable should be considered an implementation detail and can not be invoked directly.
Return the ID of that Calculator / CalculatorApp process. The fact that Calculator only ever creates one such process in a given user session actually makes identifying that process easy.
Note that this means that the PID of a preexisting Calculator process may be returned, which, however, is the correct one, because the transient process launched by Start-Process simply delegates creation of a new Calculator window to an existing process.
If you wanted to identify the newly created window, more work would be required: You'd have to enumerate the process' windows and identify the one with the highest z-order.
PowerShell code (note: in Windows 11, replace Calculator with CalculatorApp):
# Launch Calculator - which may reuse an existing instance and
# merely create a new *window* - and report the PID.
Start-Process -ErrorAction Stop calculator:
(Get-Process Calculator | Where-Object SessionId -eq (Get-Process -ID $PID).SessionId).ID
Note that I've used the URL scheme calculator: as a simpler way to launch Calculator.
Note:
The Where-Object SessionId -eq (Get-Process -ID $PID).SessionId guards against mistakenly considering potential Calculator processes created by other users in their own sessions (Get-Process returns all processes running on the local machine, across all user sessions). Filtering by .SessionID, i.e. by the active user session (window station), prevents this problem.
As a PowerShell CLI call:
powershell.exe -NoProfile -Command "Start-Process -ErrorAction Stop calculator: ; (Get-Process Calculator | Where-Object SessionId -eq (Get-Process -ID $PID).SessionId).ID"

How to close other PowerShell windows from script

I have a PowerShell script which has the following steps:
Opens another PowerShell window
Navigates to an angular projects directory
Runs a command to serve the project
Is there a way that I can close all other running PowerShell windows, but keep the currently running script and it's newly created window open? Following the changes, I would like it to behave like this:
Close all other PowerShell windows
Opens another PowerShell window
Navigates to an angular projects directory
Runs a command to serve the project
You could use Get-Process to enumerate all running powershell processes, then filter out the current one by comparing with the value of $PID, before piping the rest to Stop-Process:
Get-Process powershell |? Id -ne $PID |Stop-Process -Force
You can include the child process by ID if necessary:
$childProcess = Start-Process powershell $childProcArgs -PassThru
Get-Process powershell |? Id -notin #($PID;$childProcess.Id) |Stop-Process -Force
... although I would suggest simply killing all other powershell instances first, and then launch the child process after
Is there a way that I can close all other running PowerShell windows,
but keep the currently running script and it's newly created window
open?
$Previous = Get-process -Name *Powershell*;
{YOUR SCRIPT}
Stop-process $previous

Windows Server: How do I find out why a PowerShell process keeps starting and what it does?

I'm seeing a PowerShell process that keeps starting, and I don't know why.
According to Process Explorer the PowerShell process looks like this:
powershell -NoP -NonI -W Hidden -exec bypass "$am = ([WmiClass] 'root\default:systemcore_Updater8').Properties['am'].Value;$deam=[System.Text.Encoding]::ASCII.GetString([System.Convert]::FromBase64String($am));iex $deam;$co = ([WmiClass] 'root\default:systemcore_Updater8').Properties['enco'].Value;$deco=[System.Text.Encoding]::Unicode.GetString([System.Convert]::FromBase64String($co));iex $deco"
Something that converts from Base 64 string looks fishy to me, but apart from that, I can't decode (ha!) what's going on here.
When I kill the process it restarts at some time (few minutes to half an hour)
I've been unable to find any thing in Task Manager that seems to start the process.
I'm starting to suspect something very fishy.
Any suggestions?
Not an answer but it doesn't fit in comments:
You can execute following commands to show you what the script is invoking (iex)
$am = ([WmiClass] 'root\default:systemcore_Updater8').Properties['am'].Value;
$deam=[System.Text.Encoding]::ASCII.GetString([System.Convert]::FromBase64String($am));
Write-Output $deam
$co = ([WmiClass] 'root\default:systemcore_Updater8').Properties['enco'].Value;
$deco=[System.Text.Encoding]::Unicode.GetString([System.Convert]::FromBase64String($co));
Write-Output $deam

TASKKILL command works properly outside Script, but not inside of it

Few days ago I started developing a Powershell script which monitors a service. Command:
taskkill /f /fi "USERNAME eq admin" /im tm1top.exe
When I ran taskkill to stop one process inside my script it didn’t work: that process remained in Running, hence the script was not able to end properly.
On the other hand, running exactly the same command (taskkill) from CMD directly was successful.
NOTE: the user which is running this script has ADMIN RIGHTS on the computer and I am running Windows Seever 2008. Also tried to create a task into Windows Scheduler and to run it with highest privileges with this user, but the same result..
Could you please advise what should I modify in order to make this function work directly from my ps script?
I would recommend using WMI for this:
Get-WmiObject Win32_Process | Where-Object {
$_.GetOwner().User -eq 'admin' -and
$_.Name -eq 'tm1top.exe'
} | ForEach-Object {
$_.Terminate()
}

How do I start multiple Windows Services at once, with one command?

My primary computer for programming is the same computer I use for gaming etc. So to increase speed while gaming I turned off services like Apache, MySQL, Subversion etc. from starting at boot as I use it about 50/50 for gaming/programming.
This is fine most of the time but it's a bit of a nuisance to start them all separately.
Could someone show me how to write a batch file or something similar to start all the services?
Well you can write a batch file like
net start "Service Name"
There should be a way to dependency link the services together also, so when one starts all the others will too. I'll see if I can find the switch to do that.
EDIT:
I haven't tried this, but this should tell you where to find in the registry to make the services dependent on each other and all start automatically:
http://www.softwaretipsandtricks.com/windowsxp/articles/490/1/Removing-Service-Dependencies
You can also have the services start in parallel by calling:
SC START servicename
I don't know if that helps...
I wouldn't mess with the dependencies for services unless you really know what you're doing.
The command for starting a service is "net start <servicename>". Just add the ones you need to a file called Something.bat and run it. simple. :)
net stop <service name> will also stop them.
If you're using powershell, you can do this:
"service1", "service2" | %{ start-service $_ }
To explain the above, it's as follows:
create an array containing "service1" and "service2"
pipe that array to the foreach command (which is the % sign)
the foreach command will run the code block (delimited by { } ), and the "current item" is represented by $_
It will therefore run start-service on each of the things in your array
simply use powershell if you have a common name
Start Services
Get-Service *pattern* | start-service
Stop Services
Get-Service *pattern* | stop-service
I am a tad late on this, though I was researching something similar.
create a batch file and in that batch file use the sc command:
sc start "first servicename"
sc start "second servicename"
and so on...
save the batch file and either double click it to run it, or schedule it to run accordingly.
Like other answers mentioned, writing a batch/cmd file works wonders.
#echo off
echo Press any key to start the Services
echo ===================================
pause
echo Starting Apache
net start Apache
echo Starting MySQL
net start MySQL
echo Starting Subversion
net start Subversion
echo == Services have started ==
timeout 3
exit /b
An easier way:
Install ps tools (it has a lot of really cool cmd line tools for developers)
One of the tools that ps tools comes with is PsService
you can start stop your services using start and stop
Although I'm late to the party , however here is exactly what you need.
ProgramUtilityv1
I was looking for such application too, so i wrote it myself. It works only on Windows and that too on Windows Vista and above.I'll soon release a linux version too.
If you want to start several services at once and still wait for them to start you can do the following:
workflow work {
param(
[Parameter (Mandatory = $true)]
[Collections.Generic.List[string]]$list)
Foreach -parallel ($s in $list)
{
Start-Service $s
}
}
$list = Get-Service -Name "servicename*" -ErrorAction SilentlyContinue | foreach{$_.DisplayName}
work -list $list
With this:
you dont have inmediate return. If you dont care if service-start failed you can go with sc, net start or ps tools options.
Services are started at the same time

Resources