Powershell Script to find log files more then 10 MB and send mail whenever a new file generated in that folder -
i need find new files in folder on 10mb in size, , send mail name of files.
tricky part: mail should send when there new file arrives in folder, have keep track , differentiate between old file , new file.
problem: have written following code, , not able build logic mail. how can identify new file comes , trigger mail?
$namearray = @() $n = gci 'c:\users\rf\local\reuselibrary\familysavedirectory' | % {get-item $.fullname| ? { $.length -gt 10mb }} foreach($a in $n) { $namearray += $a.name } $namearray send-mailmessage -to *@gmail.com -from '****@*.com' -subject "add user $namearray nx license" -body "script execute $namearray successfully.." -smtpserver 'mail.****.de'
thank question! learned lot trying solve :-)!
as pointed out in comments, can use filesystemwatcher
object monitor filesystem. got little more tricky using object, because need able files in folder, not newly created ones.
another question be, should script trigger mail everytime has new item in $namearray
? maybe you'll flood of e-mails then.
it's better use function instead of script task because have more flexibility, can check newly created files, , files inside folder.
please try function. couldn't test well, because don't have folder 10mb large files created time.
usage:
to files (the wildcard * in filter important!):
get-files -filter '*.txt' -folder 'c:\yourfolder' -allfiles
to monitor new created files:
get-files -filter '*.txt' -folder 'c:\yourfolder' -newfiles
function:
please edit send-mailmessage
part receive mail on account.
function get-files() { param( [string]$filter, [string]$folder, [parameter(parametersetname='allfiles')] [switch]$allfiles, [parameter(parametersetname='newfiles')] [switch]$newfiles ) # preparing name array [string[]]$namearray = @() if(!$newfiles.ispresent) { #getting files inside folder , more 10mb $files = gci $folder | % { get-item $_.fullname | ? { $_.length -gt 10mb -and $_.extension -like $filter} } | % { $namearray += $_.fullname } # send e-mail $secondnamearray = $namearray | out-string send-mailmessage -to '*@gmail.com' -from '****@*.com' -subject "add user namearray nx license" -body $secondnamearray -smtpserver 'mail.****.de' $namearray = "" } # monitoring of files $monitoring = new-object system.io.filesystemwatcher $monitoring.filter = $filter $monitoring.path = $folder $monitoring.enableraisingevents = $true $event = register-objectevent -inputobject $monitoring -eventname created -action { #checking filesize $x = (get-item $eventargs.fullpath).length / 10mb if ($x -ge 1) { write-host "new item found: $($eventargs.fullpath). sending e-mail!" $namearray += $eventargs.fullpath $newnamearray = $namearray | out-string send-mailmessage -to '*@gmail.com' -from '****@*.com' -subject "add user namearray nx license" -body $newnamearray -smtpserver 'mail.****.de' $namearray = "" } }}
Comments
Post a Comment