Welcome to MSDN Blogs Sign in | Join | Help

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: }
Published Tuesday, May 08, 2007 4:06 PM by arulk

Comments

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

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() }

Wednesday, May 09, 2007 10:45 AM by dcormier

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

if ($processes.count -le  2 )

should be

if ($processes.count -lt  2 )

Otherwise a pair of processes will be ignored.

Friday, May 11, 2007 6:51 PM by Go de ke
Anonymous comments are disabled
 
Page view tracker