I have this powershell script I have been running for some time that I have had to update to include functionality. It runs on a 2003x64 Server, but last time I updated it, it was done on XP machine, now I am updating on a Win7 box. The script works fine on my Win7 v3-v4 Powershell, where as it fails on v1 on the ForEach ($Array in <<<<<
It's a pretty simple script, and I have tried modifying it to exhaustion to get it to work correctly, but can't seem to get it right. Is there a way around this, or do I have the syntax wrong for v1 that I can easily change? The below works fine in v3-v4. I am afraid if it is failing on this ForEach, and I can't resolve, it may fall on others further in the script...
#JCBIII Kill Process and Send Email Details
#Ver1 06212009 JCBIII - Find Process running "x" minutes email and kill
#Ver2 09022014 JCBIII - Match PID with Commandline, kill, email and restart
#Setting Up Mailer
$emailSmtpServer = "smtpmail.domain.com"
$emailMessage = New-Object System.Net.Mail.MailMessage
$emailMessage.From = "test@domain.com"
$emailMessage.To.Add( "me@domain.com" )
$emailMessage.Subject = "Notepad - Kill/Restart Script..."
$emailmessage.IsBodyHTML = $true
#Process Age
$startTimeLimit = (get-date) - (new-timespan -minutes 5)
#Finding defined process using Age as requirement
$processes_to_kill = get-process | where {$_.StartTime -lt $startTimeLimit -and ($_.path -like "*notepad.exe") }
$PIDs = get-process | where {$_.StartTime -lt $startTimeLimit -and ($_.path -like "*notepad.exe") } | select Id -ExpandProperty Id
$Commands1 = ForEach ($PIDArray in $PIDs) {get-WmiObject Win32_Process -Filter "name = 'notepad.exe'" | where {$_.ProcessId -like $PIDArray} | select CommandLine -ExpandProperty CommandLine }
#Function to email
if ($processes_to_kill -ne $null)
{
ForEach ($Commands in $Commands1)
{
$emailMessage.Body = "<b>Notepad Process Restarted: </b><BR>" + $Commands + "`r`n"
$SMTPClient = New-Object System.Net.Mail.SmtpClient( $emailSmtpServer)
$SMTPClient.Send( $emailMessage )
}
}
#Function to match process with Commandline, kill and restart
if ($processes_to_kill -ne $null)
{
$processes_to_kill | foreach { $_.Kill()}
ForEach ($Commandx in $Commands1)
{
Invoke-Expression "& $Commandx"
}
}The script fails in the finding defined process piece:
#Finding defined process using Age as requirement
$Commands1 = ForEach ($PIDArray in $PIDs) {get-WmiObject Win32_Process -Filter "name = 'notepad.exe'" | where {$_.ProcessId -like $PIDArray} | select CommandLine -ExpandProperty CommandLine }Error received is similar to this:
Unexpected token 'in' in expression or statement.
At line:x char:xx
Any help with this is appreciated. (Of course the process names were changed, and email information, but it is all valid for notepad.exe process as well.)