Execute batch script from powershell with feedback - powershell

I need your valuable comments/advice on how we could implement powershell script to send feedback to users during its execution based on its runtime.
Powershell script will be executing a batch script.
Clear-Host
cmd.exe "/c G:\BEKDocs\Batch\Batch1.cmd"
Write-Host "The Exit code from Batch1 is " $LastExitCode
Batch script will do some processing on its own, i want the power shell script to provide the feedback to few set of users on the below occasions through mail communication using SMTP (I have SMTP configured in the server).
When the script starts (Mail should be sent).
If the script completes within a minute.
If the script runs for more than a hour.
If the script fails.
Regards,
Naga

Use Send-MailMessage to send mail. Use Measure-Command to measure the execution time of a command. Use $LASTEXITCODE to determine whether an external command succeeded or failed.
$from = 'sender#example.com'
$to = 'recipient#example.com'
Send-MailMessage -From $from -To $to -Subject 'script started'
$time = Measure-Command { & cmd.exe /c "G:\BEKDocs\Batch\Batch1.cmd" }
if ( $time.TotalMinutes -le 1 ) {
Send-MailMessage -From $from -To $to -Subject 'script completed within 1 min'
} elseif ( $time.TotalMinutes -gt 60 ) {
Send-MailMessage -From $from -To $to -Subject 'script ran longer than 1 hour'
}
if ( $LASTEXITCODE -ne 0 ) {
Send-MailMessage -From $from -To $to -Subject 'script failed'
}

Related

kill a child process on windows using powershell

I have the below script but it seems it wont kill the child processes. How do i kill child processes?
When it runs, it looks fine but then there are dialog boxes left over and then when i check task manager the original processes are still running. Which makes me think if the script ran properly. The other weird part to this is that naturally I would see these processes (.exe programs) running active on the task bar but after the script runs they look like they aren't running. But again, I check task manager and sure enough, they are still running.
$ErrorActionPreference = "SilentlyContinue"
Stop-Transcript | Out-Null
$ErrorActionPreference = "Continue"
Start-Transcript -Path C:\Scripts\Errors\errors.log -Append
$process = Get-Process -Name "IVR1","IVR2","IVR3"
$IVR1path = "C:\IVR1"
$IVR2path = "C:\IVR2"
$IVR3path = "C:\IVR3"
if ($process) {
$Process | Stop-Process -Force
Start-Sleep -s 5
cd $IVR1path
Start-Process ".\IVR1.exe"
cd IVR2path
Start-Process ".\IVR2.exe"
cd IVR3path
Start-Process ".\IVR3.exe"
cd ..
cd ..
$From = "IVR1#example.com.au"
$To = "myemail#example.com.au"
$cc = "myemail#example.com.au"
$Subject = "**TEST** - IVR1 has been recovered"
$Body = "The IVR has been successfully recovered"
$SMTPServer = "mail.example.com.au"
Send-MailMessage -From $From -to $To -cc $cc -Subject $Subject -Body $Body -SmtpServer $SMTPServer
Stop-Transcript
}
Would anyone have any suggestions? Could it be due to child processes not being killed or the original process being hung?
I think that you've misused tools you have to achieve the goal. Use https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.management/get-process?view=powershell-4.0 and functions listed at the end of page ( all about process lifecycle ).
Side note: add more verbosity ( write-output variable values) to what your script does so you will know what is happening ( or use the debugger, because I`m not sure if most of code you pasted is even executed ).

Issue in Executing a batch script during -XX:OnOutOfMemoryError event

I have written a power shell script in my Win 2008 server, to execute the below mentioned 4 steps whenever an OutOfMemoryError occurs in the system.
Email users that the applications is going to be restarted.
stop the app service
clear cache and tmp files
start the service
email users that the service is started
The Script is given below and it is working like a gem when executed manually. I have added the below .ps1 script in a .bat file and updated the registry entry as
-server -Xms1024m -Xmx1536m -XX:MaxPermSize=256m -XX:+UseParallelOldGC -XX:OnOutOfMemoryError="D:\Support\UWD_OOM_restart.bat"
Issue: Whenever an OOM error occurs, the batch script invokes the power shell script, but only the first 3 steps are getting executed automatically. The last 2 steps( starting the service and emailing end users are not getting executed automatically). Need some assistance in this case
Power shell script:
$hostname = 'XXXXXX'
$smtpServer = 'xxxxxxxx'
$from = "xxxxxxxx#xxxxxxxx.com"
$recipients = 'xxxxxxxx#xxxxxxxx.com'
$Subject = "Restarting Apps - UWD Service on $hostname due to Java OUT OF MEMORY ERROR"
$body = "This is an automated message to confirm that the UWD service on xxxxxxxx server is about to be restarted, as the application has encountered Java out of memory error and went to unresponsive state. Kindly ignore any alerts for the next 10 minutes from this service."
Send-MailMessage -To $recipients -Subject $Subject -Body $body -From $from -SmtpServer $smtpServer
# Stop service
$service = 'xxxxxxxx"
Stop-Service -name $service -Verbose
do {
Start-sleep -s 5
}
until ((get-service $service).Status -eq 'Stopped')
# Folder delete
rm -r -fo 'D:\xxxxxxx\cache'
rm -r -fo 'D:\xxxxxxx\tmp'
# Start service
start-Service -name $service -Verbose
do {
Start-sleep -s 5
}
until ((get-service $service).Status -eq 'Running')
# Send confirmation that service has restarted successfully
$Subject = "UWD Service Restarted Successfully on $hostname"
$body = "This mail confirms that the UWD application service on $hostname is now running.
Application Team, Kindly smoke test your application and inform xxxxxx for any issues."
Start-Sleep -s 5
Send-MailMessage -To $recipients -Subject $Subject -Body $body -From $from -SmtpServer $smtpServer

$Env:ComputerName doesnt work with powershell Send-MailMessage in batch file

After a lot of errors and edits I got the Send-MailMessage to work through a command prompt. Below iteration sends out the emails perfect.
powershell Send-MailMessage -From " `<user#domain>`" -To " `<user#domain.com>`" -Subject 'Some subject goes here' -Body 'Some body with alert regarding Host: $env:computername. List of deleted files is attached.' -Attachments 'C:\somefile.txt' -Priority High -dno onSuccess, onFailure -SmtpServer 'smtp.domain.com'
However, this does not fetch the computername in the body. I have tried running this command in powershell directly and it works with the computername variable in body.
To get it to simply send out mails, I have already tried doing
powershell -command "command" or powershell -command "{command} or
powershell -command "& {command}" and so on and it doesnt even send
out emails.
As I am now successful sending out emails, I need to have the Computername inside the body text.
Use double quotes around the argument value to have variables contained expanded.
I.e.:
-Body "Some body with alert regarding Host: **$env:computername**. ..."
Relevant reading.
Your command line in the question and your own answer relies on the fact that powershell currently has the default (position 0) argument -Command,
but as this changes from PowerShell 6.0.0beta3 on to -File
you should explicitly use at least -C as the shortest
abbreviviation for -Command.
to speed up execution I'd use the additionl parameters -NoProfile or short -NoP and -NonInteractive or -NonI
to stop cmd from trying to interpret any parameters/arguments you should double quote them all - and escape any necessary inner double quotes with a backslash \" while also replacing double quotes with single ones if ever possible.
So I'd suggest:
powershell -NoP -NonI -C "Send-MailMessage -From \"SomeWeb-Prod#domain.com\" -To \"fromuser#domain.com\" -Subject 'Some notification for SomeWeb-Prod' -Body 'Some Alert for Host: %computername% with IP: %NetworkIP% at %time%. details in attached file.' -Attachments 'C:\somefile.txt' -Priority High -dno onFailure -SmtpServer 'smtp.domain.com'"
Or, (as you partly discovered yourself):
powershell -NoP -NonI -C "Send-MailMessage -From 'SomeWeb-Prod#domain.com' -To 'fromuser#domain.com' -Subject 'Some notification for SomeWeb-Prod' -Body 'Some Alert for Host: %computername% with IP: %NetworkIP% at %time%. details in attached file.' -Attachments 'C:\somefile.txt' -Priority High -dno onFailure -SmtpServer 'smtp.domain.com'"
"$env:computername" doesnot work for me. It simply prints it as $env:computername
%computername% worked.
Here's what's working for me right now.
powershell Send-MailMessage -From " `<user#domain.com>`" -To " `<user#domain.com>`" -Subject 'Some subject goes here' -Body 'Some body with alert regarding Host: %computername%. Some file is attached.' -Attachments 'C:\somefile.txt' -Priority High -dno onSuccess, onFailure -SmtpServer 'smtp.domain.com'
Update:
The above command worked on Win7 fine, but gave errors on server 2012. Finally this is what worked on win 2012
powershell "Send-MailMessage -From "SomeWeb-Prod#domain.com" -To "fromuser#domain.com" -Subject 'Some notification for SomeWeb-Prod' -Body 'Some Alert for Host: %computername% with IP: %NetworkIP% at %time%. details in attached file.' -Attachments 'C:\somefile.txt' -Priority High -dno onFailure -SmtpServer 'smtp.domain.com'"
It works for me, by using double quotes around variables.
I am using batch script to call powershell Send-MailMessage
Batch Script:send_email.bat
C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe -windowstyle hidden -command 'E:\path\send_email.ps1
Pwershell Script send_email.ps1
Send-MailMessage -From "noreply#$env:computername" -To '<target_email#example.com>' -Subject 'Blah Blah' -SmtpServer 'smtp.domain.com' -Attachments 'E:\path\file.log' -BODY "Blah Blah on Host: $env:computername "

Checking for a running process and if its not found, starting it

I'm trying to write a short script to run each morning on a machine to check for two programs and if they aren't running, to start them. I've made this:
$process = "ProcessToStart"
$check = Get-Process $process
$executable = "ProcessFilePath"
if (!($check)) {
Start-Process $executable
Send-MailMessage -From "Machine" -To "IT" -Subject "Program was restarted" -Body "The program wasnt running" -SMTP "mail.blah.com"
}
$process = "outlook"
$executable = "C:\Program Files\Microsoft Office 15\root\office15\outlook.exe"
if (!($check)) {
Start-Process $executable
Send-MailMessage -From "Machine" -To "IT" -Subject "Program was restarted" -Body "The program wasnt running" -SMTP "mail.blah.com"
}
The problem I have is, last week it worked, and only launched/emailed if the process wasn't running. I've retested it this week and it's launching and emailing even if the processes are already running and I can't figure out what's different.

Email credentials when using send-mailmessage command

I have searched through many many forums and they do explain how to do this but the technical language is just too difficult to understand as I'm very new to powershell. I would like this explained to me step by step (baby steps). I would like to run this powershell command in a batch file (.bat). I have a batch file that does robocopy backups weekly and I want the batch file to send me a email when the backup is complete. The only issue I have is the credentials, I get a pop-up box asking for the user name and password. When I eneter this information the email will send successfully. Here is what I have;
Using: powershell V2.0 Windows 7 Ultimate
Powershell -command send-mailmessage -to emailadress#provider.com -from emailaddress#provider.com -smtp smtp.broadband.provider.com -usessl -subject 'backup complete'
$from = "example#mail.com"
$to = "example#mail.com"
$smtp = "smtpAddress.com"
$sub = "hi"
$body = "test mail"
$secpasswd = ConvertTo-SecureString "yourpassword" -AsPlainText -Force
$mycreds = New-Object System.Management.Automation.PSCredential($from, $secpasswd)
Send-MailMessage -To $to -From $from -Subject $sub -Body $body -Credential $mycreds -SmtpServer $smtp -DeliveryNotificationOption Never -BodyAsHtml
You could pass the credential object in your same command - which would avoid the popup:
Powershell -Command 'Send-MailMessage -to "emailadress#provider.com" -from "emailaddress#provider.com" -smtp "smtp.broadband.provider.com" -usessl -subject "backup complete" -credential (new-object System.Net.NetworkCredential("user","pass","domain"))'
I'd recommend storing the username/password in a somewhat more safer format, but this should do your trick.
I'm not sure you can do SMTP authentication using the send-mailmessage command. But, you can send a message through an SMTP server that requires authentication using the Net.Mail.SmtpClient object and the System.Net.Mail.MailMessage object. See How to pass credentials to the Send-MailMessage command for sending emails for a good example.
look at the last exemple of send-mailmessage helppage
you will see you can pass credential whith the parameter -credential domain01\admin01
look here Using PowerShell credentials without being prompted for a password if you dont want any prompt (save your cred in a text file)