I'm looking solution for below issue :
We reload our application everyday and it will create the log file on daily.
sometimes the log stop writing because of some issues related to CPU usage and other strange stuff.
Now we want to monitor the log file on every 5 mins, if anything doesn't get updated in the log file then it should trigger an email.
The log file keep updating every 1 min, when the reload of file goes smooth.
I need read time stamp in the log file.The log file has time stamp column , it will write content in the log file in every 5 mins. so i need to read the time stamp inside the file for every 5 mins , if anything doesn't return more then 5 mins then i should trigger alert.
Is there any way to implement the above scenario using batch script or power shell or any other idea's to monitor log file is welcome.
Thanks for the help.
You definately can use Powershell for this purpose!
Make sure you have changed Powershell Execution Policy for scripts. You can change it like this:
Set-ExecutionPolicy -ExecutionPolicy Unrestricted
Here's the simple script that would handle it. It could be made as one/two liners of course, but i tried to make it to be more readable/understandable, there:
$FilePath = 'C:\log.txt' #Log file location
$Minutes = 5 #LastWriteTime older than 5 minutes from current time.
#General email parameters
$SMTP = 'your.smtp.server.local'
$From = 'yourserviceaccount#contoso.com'
$To = 'someperson#contoso.com'
$Subject = 'Action Required'
$Body = 'Log file havent been written from more than {0} minutes!' -f $Minutes
$LastWriteTime = (Get-ItemProperty -LiteralPath $FilePath).LastWriteTime
if ($LastWriteTime -ge (Get-Date).AddMinutes(-$Minutes))
{
Send-MailMessage -SmtpServer $SMTP -Port 25 -From $From -To $To -Subject $Subject -Body $Body -Priority High
}
You could then make a Scheduled Task that will trigger the script file every N-minutes.
Related
We are working on one application and for that application there is one module called replicator and this replicator shows the status whether failed or successful in every h hrs it runs. So, I want to create a powershell script which will check the logs from my remote desktop server and email me the status of replicator .
Can somebody help me in this.
Are the logs in a text file? Does it have a particular format? Something like:
$logline = Get-Content \\path\to\file.txt -Last 1
Send-MailMessage -smtpserver smtp0 -from me#me.com -to me#me.com -Subject "Latest Result is $logline"
I have a paperless system for mileage reimbursement sheets. We have had some issues with people submitting multiple sheets and to help supervisors check for that I created a PowerShell script that does an SQL query and creates a text file with all of the supervisors. Then, it reads that list and runs another SQL query to get all of their employees names and date ranges of previously submitted mileage sheets, saves that to a CSV file and emails it to the supervisor so they can check it when approving the next set of sheets.
When I run the script from the command line it works great. I want to schedule it to run weekly. When I test it, however, it hangs. It creates the first file of supervisors. After doing some testing, (I commented out the section that sends mail) it hangs sending the first email message. I have the task scheduled to run with the same credentials I used to create the credentials file. Any suggestions?
Here is what I have to send mail
Param($User,$File)
$User="System_Mangler#familyenrichment.cc"
$password = Get-Content "SystemMangler.txt" | ConvertTo-SecureString
$credential = New-Object System.Management.Automation.PsCredential($user,$password)
That is at the very beginning of the script.
This is in the loop that sends mail. For testing purposes I am having it send everything to me rather than users.
$From = "System_Mangler#familyenrichment.cc"
$To = "ebosworth#familyenrichment.cc"
$Attachment = "c:\backup\tools\testing.csv"
$Subject = "Mileage Date Ranges"
$Body = "Here is a list of your employees and dates of previously submitted mileage sheets. When approving mileage sheets, Please check to make sure this is not a duplicate. `r`n Thank you `r`n The System Mangler"
$SMTPServer = "smtp.gmail.com"
$SMTPPort = "587"
Send-MailMessage -From $From -To $To -Subject $Subject `
-Body $Body -SmtpServer $SMTPServer -UseSsl -Port $SMTPPort `
-Credential $Credential -Attachments $Attachment
Does anyone know how to stop a process that is hung at around 45% CPU usage using powershell.
I run into having to do this alot manually and would like to:
First develop a script that can find the process by name (in this case it's a process called dfileman.exe used by an application running on a Windows 2003 server), check to see if it's stuck at equal to or greater than 45% CPU usage for more than 5 minutes and stop it if it meets the criteria. The application will start a new process the next time it needs it so I'm not worried about restarting it.
Second, use MS SCOM to monitor the dfileman.exe process, run the above script whenever it gets hung and send me an email whenever the script was run.
Any help would be greatly appreciated. Even if it's just helping me with the script.
What I have so far is:
$ProcessName = "defilman.exe"
$PSEmailServer = "smtp.company.com"
foreach ($proc in (Get-WmiObject Win32_Processor)){
if($proc.numberofcores -eq $null){
$cores++
}else{
$cores = $cores + $proc.numberofcores
}
}
$cpuusage = [Math]::round(((((Get-Counter "\Process($ProcessName)\% Processor Time" -MaxSamples 2).Countersamples)[0].CookedValue)/$cores),2)
if ($cpuusage -gt 45)
Send-MailMessage -To "Me (myaddress)" -From "Me (myaddress)" -Subject "DFileMan Process Hung" -body "An instance of $ProcessName on Server has reached a CPU Percentage of $cpuusage %. Please Kill Process Immediately"
else
Exit
Instead of a custom script, take a look at Performance Monitor. It has built-in functionality for taking actions when a counter stays long enough on specific a value.
After Perfmon has detected that the app is using too much CPU, you can use Powershell or whatever to kill the process.
So an If statement is written like this: If(test){code to run if test passes} right now you are missing the { } from that. Corrected code:
if ($cpuusage -gt 45){
Send-MailMessage -To "Me (myaddress)" -From "Me (myaddress)" -Subject "DFileMan Process Hung" -body "An instance of $ProcessName on Server has reached a CPU Percentage of $cpuusage %. Please Kill Process Immediately"
}
Hello I am trying to get an automated backup for my domain controller to a network share using a script and windows task scheduler - our domain controller is windows server 2008r2
this is the code for the script i have written as seen below, however when i run the scrip it does create the folder on the network share but fails to initiate the system state backup power shell returns this error when i run the script.
any suggestions on what i can do to resolve this issue? i am also rather new to powershell so there many be a much easier way of going about it.
many thanks
Gordon
wbadmin 1.0 - Backup command-line tool
(C) Copyright 2004 Microsoft Corp.
ERROR - One of the parameters or options specified is invalid: [quiet].
See the syntax below.
Syntax: WBADMIN START SYSTEMSTATEBACKUP
-backupTarget:<VolumeName>
[-quiet]
Description: Creates a system state backup of the local computer and stores
it on the location specified.
To use this command, you must be a member of the Backup Operators group
or Administrators group.
Parameters:
-backupTarget Specifies the location where you want to store the backup.
The storage location requires a drive letter or a GUID-based
volume of the format: \\?\Volume{GUID}.
-quiet Runs the command with no prompts to the user.
Example:
WBADMIN START SYSTEMSTATEBACKUP -backupTarget:f:
#adds windows server backup powershell snapin
Add-Pssnapin windows.serverbackup
#gets date
$date = Get-Date -Format dd.MM.yyyy
#declares backup location and adds date
$backdir = ("\\backupserver\bpdbackups\DC\$date")
#makes backup directory on network share
mkdir $backdir | out-null
#runs system statebackup
wbadmin start systemstatebackup -backupTarget:$backdir -[quiet]
#sends and email at the nd of the process
$smtp = "192.168.xxx.xxx"
$from = "Domain Controller <support#domain.com>"
$to = "Network Admin <network.helpxxx#xxx.com>"
$body = "The backup operation has been successfully done! Date: $date"
$subject = "Backup on $date"
#Send an Email to User
send-MailMessage -SmtpServer $smtp -From $from -To $to -Subject $subject -Body $body - BodyAsHtml
write-host "Backup Successful"
OK so you have a couple of problems here. Firstly square brackets around a command line switch indicates that it is optional and should not be included. Secondly I think you need to enclose the string variable since you are not calling a powershell applet.
Try changing:
wbadmin start systemstatebackup -backupTarget:$backdir -[quiet]
to
wbadmin start systemstatebackup -backupTarget:"$backdir" -quiet
I need to execute some periodic console applications that give me some results (on the console)... How can I execute it and have its return data sent to my email?
I tried to use [Diagnostics.Process]::Start() and it launches my application but i don't know how to get the return... I do not want the exitCode, I want the text that the application prints on screen.
Using PS V2 CTP3.
*** UPDATE
The solutions presented worked fine but i have a problem... this application that i need to execute is gfix from the firebird database and now i discovered a thing, I can't redirect the output of gfix to a file, if i execute on command prompt the line:
gfix.exe -v -f dabatase.gdb > c:\test.txt
it print the output on the screen and the file is empty.
Same thing if I try to assign it to a variable... I don't know what difference gfix has from the other console apps that I use, but looks like its output can't be redirected.
Has someone seeing this?
*** UPDATE 2
Even if I use Start-transcript /Stop-Transcript, although on the screen I see the gfix output, on the file there is only the commands :/
*** UPDATE 3
Found the solution here
http://edn.embarcadero.com/br/article/25605
Something like this could work:
# temporary file
$f = [io.path]::GetTempFileName()
# start process and redirect its output to the temp file
ping localhost > $f
# create and send email
$emailFrom = "user#yourdomain.com"
$emailTo = "user#yourdomain.com"
$subject = "results"
$body = (Get-Content $f) -join "`r`n"
$smtpServer = "your smtp server"
$smtp = new-object Net.Mail.SmtpClient($smtpServer)
$smtp.Send($emailFrom, $emailTo, $subject, $body)
# delete the file
remove-item $f
I think in this case [Diagnostics.Process]::Start() is not needed. Besides that there is a cmdlet Start-Process that does almost the same.
PowerShell v2 is now out, so you could consider upgrading.
Then, you can simply try:
PS > [string]$ipconfig=ipconfig
PS > send-mailmessage -to some_email -from from_email -subject PowerShell -body $ipconfig -bodyashtml -smtp my_smtp_server
Now, it depends on how complicated your command-line output is, because the above method will collapse multiple lines into a single on.