Forum Discussion

PandaPoodle's avatar
PandaPoodle
Copper Contributor
Feb 06, 2022
Solved

Copy a file and send that copy via email on a loop

Hi, I was just wondering if there is a way to copy a .txt file to a specific destination and then send that copy via email on a loop that runs every hour or so? I've tried to do it but have had no luck.

  • PandaPoodle 

     

    Some error handling and checking ๐Ÿ™‚ 

     

    function Test-FileLock {
        param (
            [parameter(Mandatory = $true)][string]$Path
        )
      
        $oFile = New-Object System.IO.FileInfo $Path
      
        if ((Test-Path -Path $Path) -eq $false) {
            return $false
        }
      
        try {
            $oStream = $oFile.Open([System.IO.FileMode]::Open, [System.IO.FileAccess]::ReadWrite, [System.IO.FileShare]::None)
      
            if ($oStream) {
                $oStream.Close()
            }
            $false
        }
        catch {
            # file is locked by a process.
            return $true
        }
    }
      
      
    while ($true) {
        #Copying file to other location but checking if it's in use first
        if ((Test-Filelock -path d:\backup\filename.txt) -eq $False) {
            Copy-Item -Path c:\temp\filename.txt -Destination d:\backup -Force:$true
      
            #Sending mail with the file
            Send-MailMessage -SmtpServer smtp.domain.local -port 25 -Subject "Emailing the file" -Body  "See attached file" -Attachments d:\backup\filename.txt -To "Email address removed" -From "Email address removed"
        }
      
        #Wait for 1 hour
        Start-Sleep -Seconds 3600
    }

10 Replies

  • And what do you have so far? You can copy files using copy-item and send an email using send-mailmessage with an attachment that contains that file. You can use a Task Schedule to run the script every hour or only once running a while ($true) {script contents with a start-sleep -seconds 3600} in it?
    • PandaPoodle's avatar
      PandaPoodle
      Copper Contributor
      So Iโ€™m very new to Powershell, so what I did was run a script that would copy the file to another file every so often. And I ran another instance of powershell that emailed that copy every so often. But they wonโ€™t run at the same time. If the copy script is running the email script wonโ€™t work. Is there a way I can have both of those tasks run in one script? Again Iโ€™m very new to powershell which is probably why Iโ€™m having such a hard time with this.
      • Harm_Veenstra's avatar
        Harm_Veenstra
        MVP
        And you can schedule this and keep it running forever ๐Ÿ™‚ Did this work for you?

Resources