Freigeben über


How Can I Delete All the Duplicates in a Set of Processes But Keep the Oldest Process?

  This blog corresponds to the scripting guy column with the same title.   I am posting the script for doing the same with PowerShell

    1: $processes = get-wmiobject -query "Select * from win32_process where name = 'notepad.exe'"
    2:  
    3: if ($processes.count -le  2 )
    4: {
    5:   return
    6: }
    7:  
    8: $datetarget = [DateTime]::Now
    9:  
   10: foreach ($process in  $processes)
   11: {
   12:    $dateholder =  $process.CreationDate
   13:    $dateholder =  $process.ConvertToDateTime($dateholder)
   14:  
   15:    if ( $dateholder -le  $datetarget)
   16:    {
   17:     $processid =   $process.ProcessID
   18:         $datetarget  =  $dateholder
   19:    }
   20:  
   21: }
   22:  
   23:  
   24: $processes = get-wmiobject -query " select * from win32_process where name='notepad.exe' AND processID <> $processid"
   25:  
   26: foreach ($process in $processes)
   27: {
   28:    $process.Terminate()
   29: }

Comments

  • Anonymous
    May 09, 2007
    Or, as a one-liner:Get-WmiObject -query "Select * from Win32_Process where name = 'notepad.exe'" | sort CreationDate -Descending | Tee-Object -Variable procs | where { $.CreationDate -gt ($procs[$procs.Count - 1]).CreationDate } | foreach { $.Terminate() }
  • Anonymous
    May 11, 2007
    if ($processes.count -le  2 )should beif ($processes.count -lt  2 )Otherwise a pair of processes will be ignored.