0

I'm currently trying to find a command line that is running on a client machine and if the command line running the script is found, I need to terminate that process id. Here is what I currently have, but I'm a bit lost on what a good way to kill that ParentProcessID.

You can see in my Get-WMIObject, I'm getting the properties of CommandLine and ParentProcess ID. I can run a foreach and -match those command lines with a string. But at this point, I don't know how to pass or link the ParentProcessID property so I can kill that ParentProcessID.

$process = "powershell.exe"
$GetCommand = Get-WmiObject Win32_Process -Filter "name = '$process'" |select CommandLine, ParentProcessID

foreach($command in $GetCommand){
    If($command -match "MyScript.ps1"){
    #kill ParentProcessID
    }

 }

Any ideas how I would accomplish this?

TheInfamousOne
  • 175
  • 1
  • 4
  • 17

1 Answers1

0

In PowerShell (unlike traditional shells) - everything is a wrapped .NET object.

This means that you can reference the properties selected with Select-Object using the . operator

$process = "powershell.exe"
$GetCommand = Get-WmiObject Win32_Process -Filter "name = '$process'" |Select-Object CommandLine, ParentProcessID

foreach($command in $GetCommand){
    if($command.CommandLine -match "MyScript.ps1"){
        Stop-Process -Id $command.ParentProcessID
    }
 }
Mathias R. Jessen
  • 157,619
  • 12
  • 148
  • 206