locked
Powershell resending the email after 5 minutes - Duplications RRS feed

  • Question

  • Hi

    I am using the below PS script to send emails in a for loop with attachment.  I am running this script every 10 minutes using windows Task. The script successfully sending the email but the issue is PS randomly sending again same email.

    I have cleared the variables  with 'Clear-Variable' and 'Remove-Variable' commands. Still there is no improvement.

    Raised with Microsoft as Send-MailMessage  cmdlet provided by them. But they are not supporting it.

    Can any one guide how I can  solve this duplication sending of the emails by script. 

    Is any Cache i need to clear once the script completed after the For loop.

    Foreach($file in $files)

    {

    $MessageTo = @{ From = test@test.com" To = "murali.dittakavi@test.com" Subject = $file.baseName Body = "test change - " +$file.basename Attachments = $file SmtpServer = "TESTSERVER IPaddress" } # Send Email with attachemnt Try { Send-MailMessage @MessageTo -ErrorAction stop $MessageToPayroll.clear() Clear-Variable -Name MessageTo -Force Remove-variable -Name MessageTo -Force # Move Emailed file to Destination Directory $destDir = "C:\TestFiles\Archive" #Remove-Item $latestFile.Fullname Copy-Item $file $destDir #Move-Item $file.Fullname -Destination $destDir Remove-Item $file.FullName -Force } Catch { # Get the date and Time $DateStamp = get-date -uformat "%Y-%m-%d_%H-%M-%S" #Create Error Log file $_ | Out-File C:\TestFiles\Log\Error_Log_$DateStamp.txt -Append Clear-Variable -Name MessageTo -Force Remove-variable -Name MessageTo -Force }

    }

    I saw below link but no use

    https://social.technet.microsoft.com/Forums/en-US/b0 fa7c48-d57e-4133-8588-bfd125f70864/duplicate-emails?forum=ITCG 


    Murali Krishna Dittakavi *********************** If my answer/post resolved your query could you mark the post as answered. If it is helpful then vote as Helpful. Thanks



    • Edited by Muarli Krishna Dittakavi Monday, September 11, 2017 5:13 AM
    • Moved by Bill_Stewart Tuesday, November 7, 2017 9:31 PM This is not "fix/debug/rewrite my script for me" forum
    Monday, September 11, 2017 3:10 AM

All replies

  • Your code cannot be doing anything as it is syntactically wrong.  

    Look closely at your closure for the "foreach" loop.


    \_(ツ)_/

    Monday, September 11, 2017 3:29 AM
  • The following is also broken:

    @{ From = test@test.com" To = "murali.dittakavi@test.com" Subject = $file.baseName Body = "test change - " +$file.basename Attachments = $file SmtpServer = "TESTSERVER IPaddress" }

    This is usually caused by unprintable characters caused by copying code from the Internet or from a non text editor.


    \_(ツ)_/

    Monday, September 11, 2017 3:31 AM
  • That is just  happened while copying code from my script to here.. 

    No syntax error in system. Just look at the commands.

    This script is running using windows task scheduler action. 

    Do we need to clear any cache ?


    Murali Krishna Dittakavi *********************** If my answer/post resolved your query could you mark the post as answered. If it is helpful then vote as Helpful. Thanks

    Monday, September 11, 2017 5:15 AM
  • It would be helpful if you formatted the code correctly.  It is hard to read as code.

    The supposedly fixed code is still full of syntax errors and would never run. You are missing quotes as well as other issues.


    \_(ツ)_/

    Monday, September 11, 2017 5:17 AM
  • Hi JRV

    I have copied the code using the  'Code editor' window only.

    sending you complete code again. 

    Add-Type -assembly "system.io.compression.filesystem"
    
    if (Test-Path "C:\TestFiles\Ready")
    
    {	
        $SourceDir = "C:\TestFiles\Ready"
        $zipfiles = Get-ChildItem $SourceDir\*.zip
        if($zipfiles)
        {
            foreach($zipfile in $zipfiles)
            {
             [io.compression.zipfile]::ExtractToDirectory($zipfile.FullName, $SourceDir)
            }
            Remove-Item $zipfile.FullName -Force
        }
    
        
        $files = Get-ChildItem $SourceDir 
        foreach($file in $files)
        {
          
    
           $MessageTo = @{
                From = "test@test.com"
                To = "murali.dittakavi@test.com"
                Subject = $file.baseName
                Body = "test change - " +$file.basename
                Attachments = $file      
                SmtpServer = "Ip address of SMTP server"      
                }
         
       
            Try
            {
                
    	        Send-MailMessage @MessageTo -ErrorAction stop
                
                Clear-Variable -Name MessageTo
    
                Remove-variable -Name MessageTo
                
    	        $destDir = "C:\TestFiles\Archive"	
    
                Copy-Item $file $destDir
                           
                Remove-Item $file.FullName -Force
                
            }
            Catch
            {
                        
    	 $DateStamp = get-date -uformat "%Y-%m-%d_%H-%M-%S"
                $_ | Out-File C:\TestFiles\Log\Error_Log_$DateStamp.txt -Append
                Clear-Variable -Name MessageTo
                Remove-variable -Name MessageTo
            }
           
        
      } 
      
    }
           


    Murali Krishna Dittakavi *********************** If my answer/post resolved your query could you mark the post as answered. If it is helpful then vote as Helpful. Thanks

    Monday, September 11, 2017 5:33 AM
  • There is no reason to have half of your code as it is relatively pointless in PowerShell.

    Use correct design to reduce the complexity of your code and to make it easier to see what is happening. 

    There still seem to be a lot of weird unprintable characters in you code and the format is sloppy making it harder to follow.

    The following is all you need.


    $errorLog = 'C:\TestFiles\Log\Error_Log_{}.txt' -f $([datetime]::Now.ToString('yyyy-MM-dd_HH-mm-ss')
    $splat = @{ From = 'test@test.com' To = 'murali.dittakavi@test.com' Subject = '' #$file.baseName SmtpServer = "TESTSERVER IPaddress" Attachments = $null Body = '' ErrorAction = 'Stop' } $files = Get-ChildItem $SourceDir Foreach ($file in $files){ Try{ $splat.Body = "test change - $($file.basename)" $splat.Subject = $file.Fullname $splat.Attackments = $file Send-MailMessage - @splat $MessageToPayroll.clear() # ???? Move-Item $file.Fullname -Destination C:\TestFiles\Archive } Catch{ $_ | Out-File $errorLog -Append } }

    Notice that it is more readable when formatted correctly and all extraneous code is removed.

    Even your hard-to-read code should not produce extraneous results so it is hard to know what you are seeing.  Perhaps you have more that one task defined fro the same code.  Remember that the task may run longer than the task interval.


    \_(ツ)_/

    Monday, September 11, 2017 5:42 AM
  • Hi JRV

    you just concentrated on aligning the code but not trouble shoot the cause of resending email. 

    Did you find anything from my code that causes to resend the file.

    How do you make sure $splat is empty before running each file

    or at the end of the for loop completed.

    That is the question.

    the powershell resending exactly after 5 minutes of whole task completed.

    when the task complete all the files are copied to Archive folder.

    How the script sending files.


    Murali Krishna Dittakavi *********************** If my answer/post resolved your query could you mark the post as answered. If it is helpful then vote as Helpful. Thanks

    Monday, September 11, 2017 6:38 AM
  • There is no need to empty the splat.  Just overwrite the changing values and reuse it. This saves a lot of pointless code and prevents the adverse memory impacts that your code is causing.

    I recommended that you address the reasons external to the script that can cause duplicates.  Did you consider them?

    When a new user with no formal programming training comes to PowerShell the tendency is to write more code than is necessary.  Until you become experienced with PowerShell and Windows write only the lines of code you fully understand.  Use the documentation available to learn how each thing works and post basic questions to these forums to help you understand what the command or Net type does.

    I suspect you may have scheduled your task to run every 5 minutes which would explain the duplicates or you could just have accidently created to identical tasks that are both running at the same time.


    \_(ツ)_/

    Monday, September 11, 2017 6:59 AM