function p4watchdog {param([Parameter(Mandatory=$true)][string]$Depot,[string]$EventLogName = 'Application',[string]$EventLogSource = "example Perforce-$env:p4server Watchdog") try { $loginResults = p4sudo $Depot } catch { write-error ("Could not SU into requested depot. Error returned: `r`n" + $error[0]) break } try { p4get-serviceDeclarations #instantiate the configuration for this service. We use global variables $watchdogCommands and $watchdogMailConfig, which are xml chunks. } catch { write-error ("Could not retrieve p4 serviceDeclarations. The error returned was: " + $error[0]) break } $servercheck = p4get-server if ($servercheck.pingsuccess.equals($true)) { $eventLogSource = "Depot Watchdog: " + $servercheck.server $processes = p4get "monitor show -l" $date = get-date $watchDogArf = [int]0 #number of events the watchdog killed. $commandNameArray = $global:watchdogCommands | gm | ?{$_.MemberType -eq "Property"} | ?{$_.Definition -match "System.Xml.XmlElement"} | %{$_.name} $SmtpBody = $global:watchdogMailConfig.SmtpBodyArray.body[0].tostring() + "\\" + $env:computername + $global:watchdogMailConfig.SmtpBodyArray.body[1].tostring() foreach ($process in $processes) #iterate through the process list { $timespan = new-timespan -hour ($process.time -split ":")[0] -minute ($process.time -split ":")[1] -second ($process.time -split ":")[2] foreach ($commandName in $commandNameArray) #for this process, compare against the array of process types we will watch for. { if (($process.command -eq $commandName) -and ($timespan.totalminutes -gt $watchdogCommands.$commandName.timeoutMinutes)) #if the process command matches one we're iterating through, and that particular configuration's timeout has been match, we will terminate the process. { $message = "Terminating " + $commandName + " process that has been lingering for at least " + $timespan.totalminutes + " minutes.`r`n" $message += "Time at detection: " + $date + "`r`n" $message += "User: " + $loginResults.user + "`r`n" $message += "Server: " + $loginResults.server + "`r`n" $message += "Process ID: " + $process.id + "`r`n" $message += "Illegal Process instantiation time: " + $date.AddHours(-$hours).AddMinutes(-$minutes).AddSeconds(-$seconds).tolocaltime() + "`r`n" $message += "Termination results:`r`n" $cmd = "p4 monitor terminate " + $process.id $message += iex $cmd $message += "`r`n" $cmd = "p4 monitor clear " + $process.id $message += "`r`n" $message += iex $cmd send-eventmessage -eventMessage $message -eventType Warning -eventID 38050 -eventLogName Application -EventLogSource $eventLogSource $watchDogArf++ #increment our watchdog event count. } } } if ($watchDogArf -gt 0) { Send-MailMessage -to $global:watchdogMailConfig.SmtpTo -subject ($global:watchdogMailConfig.SmtpSubject + $watchDogArf + " termination events executed.") -from $global:watchdogMailConfig.SmtpFrom -body $smtpBody -smtpserver $global:watchdogMailConfig.SmtpServer -priority $global:watchdogMailConfig.SmtpPriority } } }