Run Scripts in Powershell ISE from batch file - powershell

I am executing my batch file which opens the Powershell ISE and loads the script but does nothing... I would still need to run manually. Am I missing something here?
BatchFile to call Powershell:
Powershell_ise.exe C:\Users\Desktop\myscript.ps1
That the code am using to monitor the file changes in a folder and to email:
Function Register-Watcher {
param ($folder)
$filter = "logfile.txt" #all files
$watcher = New-Object IO.FileSystemWatcher $folder, $filter -Property #{
IncludeSubdirectories = $false
EnableRaisingEvents = $true
}
$changeAction = [scriptblock]::Create('
# This is the code which will be executed every time a file change is detected
$path = $Event.SourceEventArgs.FullPath
$name = $Event.SourceEventArgs.Name
$changeType = $Event.SourceEventArgs.ChangeType
$timeStamp = $Event.TimeGenerated
Write-Host "The file $name was $changeType at $timeStamp"
Send-email
')
Register-ObjectEvent $Watcher "Changed" -Action $changeAction
}
Function Send-email{
$SMTPServer = "smtp.gmail.com"
$SMTPPort = "587"
$Username = "*****#gmail.com"
$Password = "*******"
$to = "*****#gmail.com"
$subject = "Email Subject"
$body = "Insert body text here"
$attachment = "C:\Users\Desktop\AccountMapping.sdl"
$message = New-Object System.Net.Mail.MailMessage
$message.subject = $subject
$message.body = $body
$message.to.add($to)
$message.from = $username
$message.attachments.add($attachment)
$smtp = New-Object System.Net.Mail.SmtpClient($SMTPServer, $SMTPPort);
$smtp.EnableSSL = $true
$smtp.Credentials = New-Object System.Net.NetworkCredential($Username, $Password);
$smtp.send($message)
Write-Host "Mail Sent"
}
Register-Watcher "C:\Users\Desktop"

Related

FileWatcher sends multiple emails with Net.Mail.MailMessage

I'm using a FileWatcher script and everything seems to be working as far as monitoring. The problem is that when a file changes, it's set to send me an email. It emails out fine but always sends 2 emails or if i'm sending to a text, 2 texts. What's going on here? Here's my code:
$fswAuctions = New-Object IO.FileSystemWatcher $auctions, $filter -Property #{IncludeSubdirectories = $true;NotifyFilter = [IO.NotifyFilters]'FileName, LastWrite'}
Register-ObjectEvent $fswAuctions Changed -SourceIdentifier FilesChanged4 -Action {
$name = $Event.SourceEventArgs.Name
$changeType = $Event.SourceEventArgs.ChangeType
$timeStamp = $Event.TimeGenerated
$SMTPBody = "The file '$name' was $changeType at $timeStamp"
Send-ToEmail -email "myemail#whatever.com" -strBody $SMTPBody -strSubject "Auctions Module"
Write-Host "The file '$name' was $changeType at $timeStamp" -fore white
}
function Send-ToEmail([string]$email, [string]$strBody, [string]$strSubject){
$message = new-object Net.Mail.MailMessage
$message.From = "do_not_reply#site.com"
$message.To.Add($email)
$message.Subject = $strSubject
$message.Body = $strBody
$smtp = new-object Net.Mail.SmtpClient("127.0.0.1", "25")
$smtp.Credentials = New-Object System.Net.NetworkCredential($Username, $Password)
$smtp.send($message)
}

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
}
}

How can I embed HTML File in email body

How can I use powershell to embed an HTML file in email body? This is what I have so far:
##Connect to the data source using the connection details and T-SQL command we provided above, and open the connection
$connection = New-Object System.Data.OleDb.OleDbConnection $connectionDetails
$command = New-Object System.Data.OleDb.OleDbCommand $sqlCommand,$connection
$connection.Open()
##Get the results of our command into a DataSet object, and close the connection
$dataAdapter = New-Object System.Data.OleDb.OleDbDataAdapter $command
$dataSet = New-Object System.Data.DataSet
$dataAdapter.Fill($dataSet)
$connection.Close()
$body = $TableHeader
$dataSet.Tables | Select-Object -Expand Rows |
Select-Object * -ExcludeProperty Comment, RowError, RowState, Table, ItemArray, HasErrors |
ConvertTo-HTML -head $a –body $body |
Out-File $OutputFile
$ReportLink = "file://serverr/c$/Output/Report.Html"
Write-Output " Reporting"
$MailUsername = "you"
$MailPassword = "your pasword"
$cred = New-Object System.Management.Automation.PSCredential -ArgumentList #($MailUsername,(ConvertTo-SecureString -String $MailPassword -AsPlainText -Force))
Send-MailMessage -To "abc#ymail.com" -From "xyz#ymail.com" -SmtpServer Ymail -Credential $cred -Subject " Report:" -Body $ReportLink -BodyAsHtml
I am still new to powershell. Thank you in advance
Assuming the data whichever you want to change to HTML format is in $Result Array
$EmailFrom = ""
$EmailTo = ""
$SMTPServer = ""
$EmailSubject =""
$Report = "<HTML><TITLE>Title</TITLE><BODY background-color:peachpuff><font color =""#99000"" face=""Microsoft Tai le""><H2> Heading </H2></font><Table border=1 cellpadding=0 cellspacing=0><TR bgcolor=gray align=center><TD><B>Row1</B></TD><TD><B>Row2</B></TD><TD><B>Row3</B></TD><TD><B>Row4</B></TD></TR>"
Foreach($Entry in $Result)
{
$Report += "<TR>"
$Report += "<TD>$($Entry.Value1)</TD><TD>$($Entry.Value2)</TD><TD>$($Entry.Value3)</TD><TD align=center>$($Entry.Value4)</TD></TR>"
}
$Report += "</Table></BODY></HTML>"
$mailmessage = New-Object system.net.mail.mailmessage
$mailmessage.from = ($EmailFrom)
$mailmessage.To.add($EmailTo)
$mailmessage.Subject = $EmailSubject
$mailmessage.Body = $Report
$mailmessage.IsBodyHTML = $true
$SMTPClient = New-Object Net.Mail.SmtpClient($SmtpServer)
$SMTPClient.Send($mailmessage)
I needed to add this script, it works like magic
$message = new-object System.Net.Mail.MailMessage
$message.From = $from
$message.To.Add($to)
$message.CC.Add($CC)
$Subject = " put subject here"
$message.IsBodyHtml = $True
$message.Subject = $Subject
$attach = new-object Net.Mail.Attachment($attachment)
$message.Attachments.Add($attach)
$message.body = $body
$smtp = new-object Net.Mail.SmtpClient($smtpserver)
$smtp.Send($message)

$Event.SourceEventArgs.<attribute> is returning a null or empty object

I have a FileSystemWatcher program that whenever an event is raised it sends an email notifying me of where the change happened.
However, $Event.SourceEventArgs.FullPath returns empty, and the other attributes returns $null.
Relevant code:
Function Watch{
$global:FileChanged = $false
$folder = "\\foo\boo\here\is\folder"
$filter = "*this is the filter*"
$watcher = New-Object IO.FileSystemWatcher $folder, $filter -Property #{
IncludeSubdirectories = $true
EnableRaisingEvents = $true
}
# Start-Sleep -Seconds 1
Register-ObjectEvent $watcher "Changed" -Action {$global:FileChanged = $true} > $null
# Register-ObjectEvent $watcher "Created" -Action {$global:FileChanged = $true} > $null
# Register-ObjectEvent $watcher "Deleted" -Action {$global:FileChanged = $true} > $null
# $watcher.EnableRaisingEvents = $true
while($true){
while($global:FileChanged -eq $false){
Start-Sleep -Milliseconds 250
}
$global:FileChanged = $false
$paths = $Event.SourceEventArgs.FullPath
$name = $Event.SourceEventArgs.FileName
$changetype = $Event.SourceEventArgs.ChangeType
$TimeChanged = $Event.TimeGenerated
RunScript $paths, $name, $changetype, $TimeChanged
}
}
Function RunScript
{
param($paths, $name, $changetype, $TimeChanged)
Write-Host "This should work $paths $name $changetype $TimeChanged"
$From = "email"
$ToAddress = "email"
$MessageSubject = "Form Submitted by $paths"
$MessageBody = "File Path: $Event.SourceEventArgs.FullPath
Name: $name
Change Type?: $changetype
Time Changed: $timechanged"
$SendingServer = "999.999.999.9.9"
$SMTPMessage = New-Object System.Net.Mail.MailMessage $From, $ToAddress,
$MessageSubject, $MessageBody
$SMTPClient = New-Object System.Net.Mail.SMTPClient $SendingServer
$SMTPClient.Send($SMTPMessage)
}
Watcher
Updated example. Note: I haven't tested this at all so be aware there are likely bugs. I've added some comments and a couple of different approaches for other sections of the code.
Function Watch {
$folder = "\\foo\boo\here\is\folder"
$filter = "*this is the filter*"
$watcher = New-Object IO.FileSystemWatcher $folder, $filter -Property #{
IncludeSubdirectories = $true
EnableRaisingEvents = $true
}
# Start-Sleep -Seconds 1
Register-ObjectEvent $watcher "Changed" > $null
# Register-ObjectEvent $watcher "Created" > $null
# Register-ObjectEvent $watcher "Deleted" > $null
# $watcher.EnableRaisingEvents = $true
while($true){
Wait-Event | Get-Event | ForEach-Object {
# $paths = $_.SourceEventArgs.FullPath
# $name = $_.SourceEventArgs.FileName
# $changetype = $_.SourceEventArgs.ChangeType
# $TimeChanged = $_.TimeGenerated
# If you comma-delimit this list you pass all of the arguments into "RunScript".
# Either name the parameters or make them positional.
# Positional:
# RunScript $paths $name $changetype $TimeChanged
# Named:
# RunScript -Paths $paths -Name $name -ChangeType $changetype -TimeChanged $TimeChanged
# Or use Splatting:
$params = #{
Paths = $_.SourceEventArgs.FullPath
Name = $_.SourceEventArgs.FileName
ChangeType = $_.SourceEventArgs.ChangeType
TimeChanged = $_.TimeGenerated
}
RunScript #params
}
}
}
Function RunScript {
param($paths, $name, $changetype, $TimeChanged)
Write-Host "This should work $paths $name $changetype $TimeChanged"
# $From = "email"
# $ToAddress = "email"
# $MessageSubject = "Form Submitted by $paths"
# $MessageBody = "File Path: $Event.SourceEventArgs.FullPath
# Name: $name
# Change Type?: $changetype
# Time Changed: $timechanged"
# $SendingServer = "999.999.999.9.9"
# $SMTPMessage = New-Object System.Net.Mail.MailMessage $From, $ToAddress,
# $MessageSubject, $MessageBody
# $SMTPClient = New-Object System.Net.Mail.SMTPClient $SendingServer
# $SMTPClient.Send($SMTPMessage)
# Is there a reason you're not using Send-MailMessage?
# Splatting again :)
# The body of the email isn't going to be very pretty, but it's a start.
$params = #{
From = "email"
To = "email"
Subject = "Form Submitted by $paths"
Body = "File Path: $paths
Name: $name
Change Type?: $changetype
Time Changed: $timechanged"
"
SmtpServer = "999.999.999.9.9"
}
Send-MailMessage #params
}
Now you get a caveat. The FileSystemWatcher is useful, but because of how Windows works you may well receive two event notifications for a single change (that's a deep Windows problem as opposed to a code problem). Try it and see.
Chris
Edit: Forgot to remove the action parameter. It's gone now.

Can't send email through Powershell

I have been trying to use this script as a simple boolean that checks for a file, and sends a success email, or a failure email. But I cannot for the life of me figure out why it doesn't work.
Any ideas?
$SMTPServer = "smtp.gmail.com"
$SMTPPort = "587"
$Username = "xxxx#xxxxx.com"
$Password = "xxxxxxx"
$to = "xxx#xxxxx.net"
if ( ([System.Io.fileinfo]'E:\GD Backup Folder\backup\Backup_*.zip').LastWriteTime.Date -ne [datetime]::Today ) {
$message = New-Object System.Net.Mail.MailMessage
$message.subject = "Backup Successful"
$message.body = "Backup was successful."
$message.to.add($to)
$message.from = $username
$smtp = New-Object System.Net.Mail.SmtpClient($SMTPServer, $SMTPPort);
$smtp.EnableSSL = $true
$smtp.Credentials = New-Object System.Net.NetworkCredential($Username, $Password);
$smtp.send($message)
write-host "Mail Sent"
}else{
$message = New-Object System.Net.Mail.MailMessage
$message.subject = "Backup Unsuccessful"
$message.body = "Backup was NOT Successful - File Not Found"
$message.to.add($to)
$message.from = $username
$smtp = New-Object System.Net.Mail.SmtpClient($SMTPServer, $SMTPPort);
$smtp.EnableSSL = $true
$smtp.Credentials = New-Object System.Net.NetworkCredential($Username, $Password);
$smtp.send($message)
write-host "Mail Sent"
}
Send email with attachment using powershell -
$EmailTo = "udit043.ur#gmail.com" // abc#domain.com
$EmailFrom = "udit821#gmail.com" //xyz#gmail.com
$Subject = "zx" //subject
$Body = "Test Body" //body of message
$SMTPServer = "smtp.gmail.com"
$filenameAndPath = "G:\abc.jpg" //attachment
$SMTPMessage = New-Object System.Net.Mail.MailMessage($EmailFrom,$EmailTo,$Subject,$Body)
$attachment = New-Object System.Net.Mail.Attachment($filenameAndPath)
$SMTPMessage.Attachments.Add($attachment)
$SMTPClient = New-Object Net.Mail.SmtpClient($SmtpServer, 587)
$SMTPClient.EnableSsl = $true
$SMTPClient.Credentials = New-Object System.Net.NetworkCredential("udit821#gmail.com", "xxxxxxxx"); // xxxxxx-password
$SMTPClient.Send($SMTPMessage)