Kill remote process which age is more than 15mins

Welcome Forums General PowerShell Q&A Kill remote process which age is more than 15mins

This topic contains 1 reply, has 2 voices, and was last updated by

 
Moderator
4 months, 1 week ago.

  • Author
    Posts
  • #129767

    Participant
    Points: 11
    Rank: Member

    Hi,

    I wrote a script which will kill a process on multiple servers which age is more than 15mins. Below is the script:

    
    $ServerList = Get-Content Servers.txt
    #mail configuration
    $FromAddress = "XXXXX"
    $ToAddress = "XXXXX"
    $SendingServer = "XXXXX"
    
    foreach( $Server in $ServerList)
    {
    $startTimeLimit = (get-date) – (new-timespan -minutes 15)
    $processes_to_kill = get-process | where {($_.Name -eq "winword") -and
    ($_.StartTime -lt (get-date).addminutes(15)) }
    if ($processes_to_kill -ne $null)
    {
    $processes_to_kill | foreach { $_.Kill() }
    
    $MessageSubject = "winword.exe process found running over 15 min's & killed on ${server}"
    $MessageBody ="${server} – winword.exe process found running over 15 min's & killed"
    $SMTPMessage = New-Object System.Net.Mail.MailMessage $FromAddress, $ToAddress, $MessageSubject, $MessageBody
    
    #Send the message
    $SMTPClient = New-Object System.Net.Mail.SMTPClient $SendingServer
    $SMTPClient.Send($SMTPMessage)
    }
    }
    
    

    But, the above script is not killing it. Can someone help me on this, If I am missing something. It would be great, If I can get the PID of the process aswell after killing.

    Thanks,

    Kalyan

  • #129768

    Moderator
    Points: 1,991
    Helping Hand
    Rank: Community Hero

    Time for you to look into the help documentation of Get-Process cmdlet.

    This is how we get a process with a specific name.

    Get-Process -Name winword
    

    Getting all process and filtering with Where cmdlet is not the way to achieve it.

    cmdlet to terminate a process is Stop-Process,

    Get-Process -Name winword | Where-Object -FilterScript {#whatever filter} | Stop-Process
    

    TO get the PID use -PassThru parameter.

    $Process = Get-Process -Name winword | Where-Object -FilterScript {#whatever filter} | Stop-Process -PassThru
    $Process.Id
    

The topic ‘Kill remote process which age is more than 15mins’ is closed to new replies.

denizli escort samsun escort muğla escort ataşehir escort kuşadası escort