Batch script to taskkill search by "Command Line" arguments - powershell

I need a batch script to taskkill by "Command Line" arguments ("Command Line" from Windows Task Manager). To clarify - these processes are dotnet core applications. They are started via:
dotnet MyDotnetCoreApp.dll xxx yyy
If you examine under Task Managers,
Name = dotnet.exe
Image path name = C:\Program Files\dotnet\dotnet.exe
Command line = dotnet MyDotnetCoreApp.dll xxx yyy
I need a batch script to kill these tasks, probably with taskkill
OPTION 1 is Taskkill by PID but how my script search "Command Line" arguments for MyDotnetCoreApp?
OPTION 2 is taskkill by Image Name? This is no go as my server has many dotnet core applications, if kill my Image Name, all dotnet core processes be killed
I been researching:
https://superuser.com/questions/415360/how-do-i-find-out-command-line-arguments-of-a-running-program
https://www.itprotoday.com/powershell/powershell-contains
I can't get this to work, not good at PowerShell:
Get-WmiObject Win32_Process -Filter "name = 'dotnet.exe'" | Select-Object Handle
Here'd get a list of PIDs with which to kill.
Two challenges:
First Challenge, my WHERE clause dont work:
Get-WmiObject Win32_Process -Filter "name = 'dotnet.exe'" | where {$_.CommandLine -like '*MyDotnetCoreApp*'} | Select-Object Handle
I checked further, found out these "CommandLine" was NOT populated for these WmiObjects (omg!):
Get-WmiObject Win32_Process -Filter "name = 'dotnet.exe'" | Select-Object ProcessId, Name, CSName, Caption, CommandLine, ExecutablePath
I later then found out "CommandLine" would have been populated IF you run Powershell as Administrator!?! (Powershell so cryptic!)
In the end - First challenged was resolved:
Get-WmiObject Win32_Process -Filter "name = 'dotnet.exe'" | where {$_.CommandLine -like '*MyDotnetApp*'} | Select-Object ProcessId, Name, CSName, Caption, CommandLine, ExecutablePath
Second Challenge: How to kill it? Found it!!
(Get-WmiObject Win32_Process -Filter "name = 'dotnet.exe'" | where {$_.CommandLine -like '*MyDotnetCoreApp*'}).Terminate()
So this is actually resolved!

Run Powershell as Administrator! Download psexec from https://learn.microsoft.com/en-us/sysinternals/downloads/psexec
psexec -u Administrator -p SomeSecret powershell
Then from Powershell:
(Get-WmiObject Win32_Process -Filter "name = 'dotnet.exe'" | where {$_.CommandLine -like '*MyDotnetCoreApp*'}).Terminate()
Now as separate question, can you do this one line? Below wont work because -Filter has quotes in it!
psexec -u Administrator -p SomeSecret powershell -Command "(Get-WmiObject Win32_Process -Filter ""name = 'dotnet.exe'"" | where {$_.CommandLine -like '*MyDotnetCoreApp*'}).Terminate() "
As hacky work around, I removed -Filter clause (How unfortunate, not sure how to escape quotes):
psexec -u Administrator -p SomeSecret powershell -Command "(Get-WmiObject Win32_Process | where {$_.CommandLine -like '*MyDotnetCoreApp*'}).Terminate() "

Works for me as a regular user, unless the process is running as administrator?. Unfortunately, the filter syntax is like sql here, where '%' is the wildcard. Piping to where-object would probably work just as well.
get-wmiobject win32_process -filter "commandline like '%dotnet.exe%MyDotnetCoreApp%'" |
remove-wmiobject
get-wmiobject win32_process | where commandline -like '*dotnet.exe*MyDotnetCoreApp*' |
remove-wmiobject

Related

PowerShell: kill/find all processes for current user except whitelist

On my CI (Jenkins) slaves, I'd like to kill all leftover processes after/before a build. (Yes, I know that Jenkins tries to do this for me, but doesn't always succeed).
The heuristic is :
Current User processes only
Except a process whitelist (any process essential for jenkins agent) eg:
jenkins-swarm
conhost type things.
I found ways to find current user's processes, and I found ways to kill processes, but not how to combine them (ideally into a one-liner)
This is what I have Jenkins run pre/post build (Tested on Windows Server 2016):
Remove backticks if using as a one-liner
(Get-WmiObject -Class Win32_Process `
| ? { ([System.Security.Principal.WindowsIdentity]::GetCurrent().Name) -match $_.GetOwner().User } `
| ? {$_.CommandLine -notmatch 'conhost|swarm|jenkins-.*bat' -and $_.Name -notmatch 'System Idle|^System$' } `
).Terminate()
And to list them visually (I run this before I run the terminate version above), last line is different:
(Get-WmiObject -Class Win32_Process `
| ? { ([System.Security.Principal.WindowsIdentity]::GetCurrent().Name) -match $_.GetOwner().User } `
| ? {$_.CommandLine -notmatch 'conhost|swarm|jenkins-.*bat' -and $_.Name -notmatch 'System Idle|^System$' } `
) | Select-Object Handle,Name,CommandLine | Format-List | Out-String -width 9999
Both are run via powershell -c

PowerShell script to identify and stop one specific service

I try to make a PowerShell script to do the following:
I want to identify the antivirus running on my PC.
I use command to do that:
$AntiVirusProduct = Get-WmiObject -Namespace root\SecurityCenter2 -Class AntiVirusProduct
Write-Output $AntiVirusProduct.DisplayName
Here I get the antivirus name but, I don't know how to grep the antivirus name and put it to the next command.
The next command is:
Stop-Service -Force "$Antivirus Name"
Or if there is a better way to to this?
Edit
Get-WmiObject -Namespace root\SecurityCenter2 -Class AntiVirusProduct |
Select DisplayName
DisplayName
-----------
AVG Antivirus
Windows Defender
If your display name output is a list of service names you can remove the Windows Defender entry from the list with something like this:
$svc = $AntiVirusProduct.DisplayName |
Where-Object { $_ -notlike '*Windows Defender*' }
and then stop the service like this:
$svc | Stop-Service -Force

Kill multiple processes running from a given path on remote machine

I have a following problem:
I'm in need of a code that will close all running process from a given path on a remote machine.
So far I've found and came up with those 2 lines but none of them actually work.
Get-Process | Where-Object {$_.Path -like "\\$computername\C$\Program Files (x86)\Adobe\Adobe Reader 10.0\Reader\**"} | Stop-Process -Force
This is the second line I've found but still does not want to work with me :)
Get-WmiObject Win32_Process -Filter "ExecutablePath LIKE '\\$computername\C$\Program Files (x86)\Adobe\Adobe Reader 10.0\Reader\'" -ComputerName $computername | Invoke-WmiMethod -Name Terminate
I will be happy to get some advice. Belive that this is something rather simple to do..I hope that is.. :)
Something like this should work:
(Get-WmiObject Win32_Process -ComputerName $computerName | ?{ $_.ExecutablePath -like "*Program Files (x86)\Adobe\Adobe Reader 10.0\Reader*" }).Terminate()
You might have to tweak the "like" expression, however.
Another way to approach this is to run that command local to the machine with PSRemoting.
Invoke-Command $computername -script {
Get-Process | Where-Object {$_.Path -like "c:\Program Files (x86)\Adobe\Adobe Reader 10.0\Reader\*"} | Stop-Process -Force
}

show process's full command line in powershell?

When I run this command
PS C:\> gwmi Win32_Process | select CommandLine
It cuts off the command line. How can I get it to show the full command line?
That being done by the default formatting, which is using Format-Table. Try format-list
gwmi win32_process | select commandline | format-list
Alternatively Format-Table offers the -wrap and -autosize parameters.
gwmi win32_process | select handle, commandline | ft -wrap -autosize
Results
466 %SystemRoot%\system32\csrss.exe ObjectDirectory=\Windows SharedSection=1024,20480,768 Windows=On SubSystemType=Windows ServerDll=bas
esrv,1 ServerDll=winsrv:UserServerDllInitialization,3 ServerDll=winsrv:ConServerDllInitialization,2 ServerDll=sxssrv,4 ProfileContro
l=Off MaxRequestThreads=16
550 wininit.exe
510 %SystemRoot%\system32\csrss.exe ObjectDirectory=\Windows SharedSection=1024,20480,768 Windows=On SubSystemType=Windows ServerDll=bas
esrv,1 ServerDll=winsrv:UserServerDllInitialization,3 ServerDll=winsrv:ConServerDllInitialization,2 ServerDll=sxssrv,4 ProfileContro
l=Off MaxRequestThreads=16
546 C:\Windows\system32\services.exe
596 C:\Windows\system32\lsass.exe
3472 "C:\Program Files (x86)\Mozilla Firefox\firefox.exe"
1766 "C:\Windows\system32\notepad.exe"
3384 "C:\WINDOWS\system32\WindowsPowerShell\v1.0\powershell.exe"
1780 \??\C:\Windows\system32\conhost.exe
You're better off filtering for specific process which can be done via PID or Process Name, both pieces of information are easily obtained from the task manager if you don't already know.
Once you have the PID this will work great:
$PID=<Your Process ID)
(Get-WmiObject win32_process -Filter ProcessId=$PID -Property CommandLine).CommandLine
Example of getting java.exe by process name:
(Get-WmiObject -Class win32_process -Filter "Name='java.exe'" -Property CommandLine).CommandLine
added by barlop
example with output-
PS C:\Users\User> (Get-WmiObject win32_process -Filter ProcessId=1676 -Property CommandLine).CommandLine <ENTER>
"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" --type=renderer --field-trial-handle=1108,1777349067310493
8616,10462310811264875730,131072 --lang=en-GB --enable-auto-reload --origin-trial-disabled-features=MeasureMemory --devi
ce-scale-factor=1 --num-raster-threads=2 --enable-main-frame-before-activation --renderer-client-id=1695 --no-v8-untrust
ed-code-mitigations --mojo-platform-channel-handle=11412 /prefetch:1
PS C:\Users\User>
This is a frequently asked question about how powershell formats output. Aside from making the window bigger:
gwmi Win32_Process | % CommandLine
sihost.exe
C:\Windows\system32\svchost.exe -k UnistackSvcGroup
taskhostw.exe {222A245B-E637-4AE9-A93F-A59CA119A75E}

Disable NetworkAdapter CMD

How can I run this powershell script in cmd?
$adaptor = Get-WmiObject -Class Win32_NetworkAdapter | Where-Object {$_.Name -like "*Wireless*"}
$adaptor.Disable()
Make sure CMD is elevated. You could use WMIC directly from CMD:
wmic nic where "NetConnectionID like '%wireless%'" call disable
you can pass commands to the powershell executeable via the -Command switch and prefixing the script block with &.
powershell -Command "& { $adaptor = Get-WmiObject -Class Win32_NetworkAdapter | Where-Object {$_.Name -like "*Wireless*"}; $adaptor.Disable() }"
You can read more by running the command powershell -?