Powershell Email Notification File Created - powershell

I have written a code for PowerShell to notify me when a new file has been added to a designated folder, but every time the file is opened it creates a temp file and I keep getting those emails each time I open it. I have tried to create an if-else statement so that the temp file emails go to a different email address. Ideally, I would like to not receive those emails at all. If any of you know of a way that this is possible please help me. I have copied my code below.
$folder = "File Folder Path"
$mailserver = "mailserver"
$recipient = "Recipient#Email.com"
$fsw = New-Object System.IO.FileSystemWatcher $folder -Property #{
IncludeSubdirectories = $true
EnableRaisingEvents=$true
}
$created = Register-ObjectEvent -InputObject $fsw -EventName Created -SourceIdentifier CreatedEvent -Action {
$item = Get-Item $eventArgs.FullPath
$s = New-Object System.Security.SecureString
$anon = New-Object System.Management.Automation.PSCredential ("NT AUTHORITY\ANONYMOUS LOGON", $s)
If ($fsw -ccontains '~') {
Send-MailMessage -To "MyEmail#Email.com" `
-From "Email#Email.com" `
-Subject “File Creation Event” `
-Body "A file was created: $($eventArgs.FullPath)" `
-SmtpServer $mailserver `
-Credential $anon
}
Else {
Send-MailMessage -To $recipient `
-From "Email#Email.com" `
-Subject “File Creation Event” `
-Body "A file was created: $($eventArgs.FullPath)" `
-SmtpServer $mailserver `
-Credential $anon
}
}

Contains works on an array, not a string. Use -like or -match.
If you don't want an e-mail, don't write the code to send one.
For example, this only send an e-mail if your temp file does not contain ~. As there is no else, no action is taken if the file name does contain ~.
If ($fsw -notlike '*~*') {
Send-MailMessage -To $recipient `
-From "Email#Email.com" `
-Subject “File Creation Event” `
-Body "A file was created: $($eventArgs.FullPath)" `
-SmtpServer $mailserver `
-Credential $anon
}

Related

PowerShell Email Attachment: Could not find file 'D:\20201124131044\TRACS-20201124034849\error.log environment.log RACS-20201124034849.sterr.stdout

I am trying to send out an email with only the attachments that exist in the directory. There are three sets of files i am monitoring: error.log, environment.log and a .stdout. I want to check whether each one of the files exist and if they do then add it in a list and send it out as attachments. I dont want to do anything if the files dont exist. I attempted to loop through the list of files (this is in windows) and then if the files exist send them out. My code below:
$PSEmailServer = "xxxxxxxxxxx"
$Password ="xxxxxxxxx"
$mypassword = ConvertTo-SecureString $Password -AsPlainText -Force
$mycredential = New-Object System.Management.Automation.PSCredential ("xxxxx", $mypassword)
$EmailSubject ="test"
$filepath ="D:\20201124131044\TRACS-20201124034849\"
$files = #('error.log','environment.log','TRACS-20201124034849.sterr.stdout')
$FromEmail ="xxxxxxxxxx"
if(($files | foreach{Test-path $filepath }) -contains $True){
$newfile = $filepath + $files
Send-MailMessage -From $FromEmail -To "xxxxxxx" -Subject $EmailSubject -Body "test" -Credential $mycredential -Attachments $newfile
}
else {
echo "nothing"
exit
}
when i run the above i get the following error:
Send-MailMessage : Could not find file 'D:\20201124131044\TRACS-20201124034849\error.log environment.log TRACS-20201124034849.sterr.stdout'. At C:\Users\Downloads\powershell.ps1:22 char:1
+ Send-MailMessage -From $FromEmail -To "xxxxxxx" -Subje ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [Send-MailMessage], FileNotFoundException
+ FullyQualifiedErrorId : > System.IO.FileNotFoundException,Microsoft.PowerShell.Commands.SendMailMessage
I think I need to iterate the list to attach each filename to the it's filepath and then store it in a list and then send out the email? Please advise.
You can simply use -contains or -in to find filenames in an array.
Also, I would recommend using splatting for the parameters to Send-MailMessage:
$filepath = "D:\20201124131044\TRACS-20201124034849"
$files = 'error.log','environment.log','TRACS-20201124034849.sterr.stdout'
# find files with names that can be found in the $files array
$attachments = #(Get-ChildItem -Path $filepath -File | Where-Object { $files -contains $_.Name })
# if we have any files to send
if ($attachments.Count) {
$Password = "xxxxxxxxx"
$mypassword = ConvertTo-SecureString $Password -AsPlainText -Force
$mycredential = New-Object System.Management.Automation.PSCredential ("xxxxx", $mypassword)
# use splatting for better readability
$mailParams = #{
To = "xxxxxxx"
From = "xxxxxxxxxx"
Subject = "test"
Body = "test"
Credential = $mycredential
Attachments = $attachments.FullName
SmtpServer = "xxxxxxxxxxx"
# more parameters can be added here
}
# send the email
Send-MailMessage #mailParams
}
else {
Write-Host 'Nothing to send..'
}
Try
$PSEmailServer = "xxxxxxxxxxx"
$Password ="xxxxxxxxx"
$mypassword = ConvertTo-SecureString $Password -AsPlainText -Force
$mycredential = New-Object System.Management.Automation.PSCredential ("xxxxx", $mypassword)
$EmailSubject ="test"
$attachments = Get-ChildItem "D:\20201124131044\TRACS-20201124034849" | Where-Object {$_.Name -match "error.log|environment.log|TRACS-20201124034849.sterr.stdout"}
$FromEmail ="xxxxxxxxxx"
if($attachments){
Send-MailMessage -From $FromEmail -To "xxxxxxx" -Subject $EmailSubject -Body "test" -Credential $mycredential -Attachments $attachements
}
else {
echo "nothing"
exit
}

Powershell Script to send email after validation

I have a Powershell script that logs the result to a text file (this is working fine), now I need to update it to send email instead of a Log file (see actual script below). I'm kind of a new to powershell, hopefully you can help me out.
# details of the script
# if a file "FILE.400" is found and check the modified date, it will send a log file (txt file)
# need to update the script, to send email instead of a log file
$svr=$env:ComputerName
$date=[datetime]::Today.ToString('MM-dd-yyyy')
$filename = "FILE.400"
$DestLogs1 = "E:\sample\pfupdatedfin-$date.txt"
$DestLogs2 = "E:\sample\pfoutdatedfin-$date.txt"
$SrcPath = "E:\sample\$filename"
If ((Get-ChildItem $SrcPath).LastWriteTime -gt $date)
{
$date | Out-File $DestLogs1
Write-Output "Found latest FILE.400 file" | Out-File $DestLogs1 -Append
(Get-ChildItem -Recurse -Path $SrcPath).LastWriteTime | Out-File $DestLogs1 -Append
}
Else
{
Write-Output "FILE.400 - is not updated, please verify " | Out-File $DestLogs2
(Get-ChildItem -Recurse -Path $SrcPath).LastWriteTime | Out-File $DestLogs2 -Append
}
Send-MailMessageis pretty easy to use. The online documentation for cmdlets is very easy to find. Just enter the name of the cmdlet in your favorite search engine. Or use the Get-Help cmdlet. Here is an example how to use it just fille the Variables reasonably :
Send-MailMessage -From $From -To $To -Subject $Subject -Body $Body -SmtpServer $SMTPServer -Port $SMTPPort -Credential $Credential # -UseSsl:$UseSsl
-useSsl is a switch so it is not necessary unless it's $true. If you want to provide a variable to a switch parameter, don't use a whitespace but a : in between.
Credentials in Powershell are stored in credential objects. You can't just use a plain text password. However don't think they are stored extremly save since the password can be easly extracted if you know how. Here is how you create the necessary credential object:
$SecPw = ConvertTo-SecureString -AsPlainText $Password -Force
$Credential = New-Object System.Management.Automation.PSCredential -ArgumentList $UserName,$SecPw
the script is working as expected, in my Home network
$svr=$env:ComputerName
$date=[datetime]::Today.ToString('MM-dd-yyyy')
$filename = "FILE.400"
$DestLogs1 = "E:\sample\pfupdatedfin-$date.txt"
$DestLogs2 = "E:\sample\pfoutdatedfin-$date.txt"
$SrcPath = "E:\sample\$filename"
# email settings
$MyEmail = "myemail#gmail.com"
$SMTP = "smtp.gmail.com"
$To = "samplereceiver#gmail.com"
$Subject1 = "JDA-Alert || Found FILE.400 file - Successful"
$Body1 = "JDA-Alert || Found FILE.400 file - Successful"
$Subject2 = "JDA-Alert || FILE.400 file - Outdated File"
$Body2 = "JDA-Alert || FILE.400 file - Outdated File"
$Creds = (Get-Credential -Credential "$MyEmail")
If ((Get-ChildItem $SrcPath).LastWriteTime -gt $date)
{
Start-Sleep 2
Send-MailMessage -To $To -From $MyEmail -Subject $Subject1 -Body $Body1 -SmtpServer $SMTP -Credential $Creds -UseSsl -Port 587 -DeliveryNotificationOption Never
}
Else
{
Start-Sleep 2
Send-MailMessage -To $To -From $MyEmail -Subject $Subject2 -Body $Body2 -SmtpServer $SMTP -Credential $Creds -UseSsl -Port 587 -DeliveryNotificationOption Never
}

Email Notification Powershell Getting 2 Emails

I have written a powershell script, to get an email notification when a file is saved in a certain folder. It works really well the first time anyone saves, but after that you get 2 emails anytime someone saves. Can you look at the code posted below and see what I did wrong exactly or why this might be happening?
$folder = "Folder Path"
$mailserver = "mail server"
$recipient = "Alerts#Email.com"
$fsw = New-Object System.IO.FileSystemWatcher $folder -Property #{
IncludeSubdirectories = $true
EnableRaisingEvents=$true
}
$created = Register-ObjectEvent -InputObject $fsw -EventName Created -SourceIdentifier CreatedEvent -Action {
$item = Get-Item $eventArgs.FullPath
$s = New-Object System.Security.SecureString
$anon = New-Object System.Management.Automation.PSCredential ("NT AUTHORITY\ANONYMOUS LOGON", $s)
If (($item -notlike '~') -And ([IO.Path]::GetExtension($item) -ne '.tmp')) {
Send-MailMessage -To $recipient `
-From "Email#Email.com" `
-Subject “File Creation Event” `
-Body "A file was created: $($eventArgs.FullPath)" `
-SmtpServer $mailserver `
-Credential $anon
}
}

If file exists, send Email and run batch script

I have a script that runs every two hours to see if a file has been dropped. If it is there, I get an alert. I would like to take it a step further and run a job the move the file. So far here is what I have:
$path = "\\0.0.0.0\files\test\state\WAITING\*"
$fileexists = Test-Path $path
if ($fileexists) {
Send-MailMessage `
-From noreply#email.com `
-To tester#foo.com `
-Subject "Files Have Arrived" `
-Body "The files have arrived and are being moved to the processing folder." `
-SmtpServer 0.0.0.1
} else {
#donothing
}
I want to fit this in the ifexists:
Start-Process "cmd.exe" "/c \\0.0.0.0\files\test\MOVE.bat"
Would it be like this:
$path = "\\0.0.0.0\files\test\state\WAITING\*"
$fileexists = Test-Path $path
if ($fileexists) {
Send-MailMessage `
-From noreply#email.com `
-To tester#foo.com `
-Subject "Files Have Arrived" `
-Body "The files have arrived and are being moved to the processing folder." `
-SmtpServer 0.0.0.1
Start-Process "cmd.exe" "/c \\0.0.0.0\files\test\MOVE.bat
} else {
#donothing
}
I got it figured out
$path = "\\0.0.0.0\files\test\state\WAITING\*"
$fileexists = Test-Path $path
if ($fileexists) {
Start-Process "cmd.exe" "/c \\0.0.0.1\files\test\MOVE.bat"` | Send-MailMessage -From noreply#test.com -To tester#foo.com -Subject "Files Have Arrived" -Body "The files have arrived and are being moved to the processing folder." -SmtpServer 0.0.0.2`
} else {
#donothing
}
You can use semicolon ";" to separate commands.

Attaching to an email in powershell script

I have the following powershell script:
$csv = Import-Csv -Path D:\temp\Audit.csv | Where-Object {$_.PrivateLabelSeqId -eq "602"} | Measure-Object
$Fun = $csv.Count
$mailBody =
#"
There are <b> $Fun </b> available!
"#
Send-MailMessage -Body $mailBody -BodyAsHtml `
-From "mail#mail.com" -To "mailto#mail.com" `
-Subject "Audit - FUN" -Encoding $([System.Text.Encoding]::UTF8) `
-Attachment "D:\temp\Audit.csv" `
-SmtpServer "192.0.0.20"
Yet I do not get any email sent out. Without the attachment however, it seems to work just fine. Any ideas on how to resolve this?
Thanks
I encountered the same problem once, i solved it by using System.Net.Mail instead.
$filenameAndPath = (Resolve-Path .\$file).ToString()
$from = 'mail#mail.com'
$to = "mailto#mail.com" `
$Subject "Audit - FUN" -Encoding $([System.Text.Encoding]::UTF8)
[void][Reflection.Assembly]::LoadWithPartialName('System.Net') | out-null
$message = New-Object System.Net.Mail.MailMessage($from, $to, $subject, $subject)
$attachment = New-Object System.Net.Mail.Attachment($filenameAndPath, 'text/plain')
$message.Attachments.Add($attachment)
$smtpClient = New-Object System.Net.Mail.SmtpClient
$smtpClient.host = '192.0.0.20'
$smtpClient.Send($message)
To read more about System.Net.Mail.Attachement Class
http://msdn.microsoft.com/en-us/library/system.net.mail.attachment.aspx