locked
Backup to USB drive script RRS feed

  • Question

  • Hello scripting gurus!

    I need some help in adding some additional logic to a USB backup script that I am using to copy SQL backup files from one share to another.

    What I would like to do is generate a unique event in event viewer when the backup task is started and completed. I would also like send an e-mail if the windows scheduled task fails or just fails to start. 

    I tried using windows task scheduler to send an e-mail based on an event but it doesn't seem to work properly. Even if did check for event 200, it would end up sending an e-mail for every task not just the one I am interested in. This is why I would prefer the script to generate a unique one to avoid tasks conflicts. 

    Can anyone help me with this one? Below is the code I am using.

    Much appreciated guys!



    • Edited by Spartan_007 Saturday, March 31, 2018 1:56 PM
    Friday, March 30, 2018 7:00 PM

All replies

  • Please post code correctly using the code posting tool.

    Your post is completely unreadable.


    \_(ツ)_/

    Friday, March 30, 2018 11:14 PM
  • Sorry about that. Here you go sir.
    #==========================================================================================================
    # Checks for presence of offsite backup USB drive by filepath, then backs up relevant data to drive if 
    # present, exits gracefully if not present. Schedule script to run everynight and it only backs up data 
    # when USB external drive has been inserted and turned on. 
    # (Created by Rich Hewlett, see blog at RichHewlett.com) 
    # (Post is https://richhewlett.com/2014/02/28/how-to-backup-to-usb-drive-only-if-its-connected/)
    # Uses Robocopy for copy actons but any copy tool can be used. 
    # Uses DevCon USB connection tool to cleanly disconnect USB drive (see blog post for more info) 
    #==========================================================================================================
    clear-host
    
    write-output "---------------------Script Start--------------------"
    write-output " Running Backup Script"
    write-output "-------------------------------------------------------"
     
     
    # set file paths and log file names 
    $timestamp = Get-Date -format yyyyMMdd_HHmmss
    $LogBasePath="C:\Logs\USBBackup"
    $LogFile="$LogBasePath\USBBkUp_$timestamp.txt"
    $USBDriveLetter="U"
    $USBDriveBackupPath="U:\Backup"
     
    # set error action preference so errors don't stop and the trycatch kicks in to handle gracefully
    $erroractionpreference = "Continue"
     
    try
    {
        # Check USB drive is on by verfiying the path
        if(Test-Path $USBDriveBackupPath)
        {   
            # now copy the data folders to backup drive
            invoke-expression "Robocopy C:\Docs $USBDriveBackupPath\Docs /MIR /LOG:$LogFile /NP"
            invoke-expression "Robocopy C:\Stuff $USBDriveBackupPath\Stuff /MIR /LOG+:$LogFile /NP"
             
            # Copy the log file too
            invoke-expression "Robocopy $LogBasePath $USBDriveBackupPath\Logs /MIR /NP"
                         
            # Sleep for 60 to ensure all transactions complete, then disconnect USB drive       
            Start-Sleep -Seconds 60
            Invoke-Expression "c:\DevCon\USB_Disk_Eject /removeletter $USBDriveLetter"       
        }
    }
    catch
    {
        # Catch the error, log it somewhere, but make sure you still eject the drive using below
        Start-Sleep -Seconds 60
        Invoke-Expression "c:\DevCon\USB_Disk_Eject /removeletter $USBDriveLetter"
    }
    
    write-output "------------------------------------Script end------------------------------------"

    Saturday, March 31, 2018 1:30 PM
  • Please edit you original post to make it readable.  Just click the edit button and rewrite your post then delete the new post.

    People search for issues and need to see a clear question and example code.  When many see your post they will just ignore it because it is unreadable and badly formatted.  Do not make it difficult for others to understand what you are asking.

    Thank you.


    \_(ツ)_/

    Saturday, March 31, 2018 1:41 PM
  • Thanks for the instructions Jrv and sorry about that.
    Saturday, March 31, 2018 1:58 PM
  • I see no code that send an email or a cde that writes an event. 

    To send an email use "Send-MailMessage".  To write an event use "Write-EventLog".

    I see no reason to write to the event log.  Just send the mail when the script completes.


    \_(ツ)_/

    Saturday, March 31, 2018 2:04 PM
  • Thanks Jrv. Here's what I have so far.

    How can I get notified if the Windows scheduled task that will be running this script fails? This feature in Windows 2012 is deprecated so I have to rely on powershell to accomplish this but do not know how.

    #==========================================================================================================
    # Checks for presence of offsite backup USB drive by filepath, then backs up relevant data to drive if 
    # present, exits gracefully if not present. Schedule script to run everynight and it only backs up data 
    # when USB external drive has been inserted and turned on. 
    # (Created by Rich Hewlett, see blog at RichHewlett.com) 
    # (Post is https://richhewlett.com/2014/02/28/how-to-backup-to-usb-drive-only-if-its-connected/)
    # Uses Robocopy for copy actons but any copy tool can be used. 
    # Uses DevCon USB connection tool to cleanly disconnect USB drive (see blog post for more info) 
    #==========================================================================================================
    clear-host
    
    write-output "---------------------Script Start--------------------"
    write-output " Running Backup Script"
    write-output "-------------------------------------------------------"
     
    ####Parameters being used for mail SMTP configuration and e-mail addresses
    $SMTPServer = 'smtprelay.mycompany.com'
    $From = 'donotreply@mycompany.com'
    $To = 'admin@mycompany.com'
    $Subject = "USB Backup Job"
    $body
    
    # set file paths and log file names 
    $timestamp = Get-Date -format yyyyMMdd_HHmmss
    $LogBasePath="C:\Logs\USBBackup"
    $LogFile="$LogBasePath\USBBkUp_$timestamp.txt"
    $USBDriveLetter="U"
    $USBDriveBackupPath="U:\Backup"
     
    # set error action preference so errors don't stop and the trycatch kicks in to handle gracefully
    $erroractionpreference = "Continue"
     
    try
    {
        # Check USB drive is on by verfiying the path
        if(Test-Path $USBDriveBackupPath)
        {   
            # now copy the data folders to backup drive
            invoke-expression "Robocopy C:\Docs $USBDriveBackupPath\Docs /MIR /LOG:$LogFile /NP"
            invoke-expression "Robocopy C:\Stuff $USBDriveBackupPath\Stuff /MIR /LOG+:$LogFile /NP"
             
            # Copy the log file too
            invoke-expression "Robocopy $LogBasePath $USBDriveBackupPath\Logs /MIR /NP"
                         
            # Sleep for 60 to ensure all transactions complete, then disconnect USB drive       
            Start-Sleep -Seconds 60
            Invoke-Expression "c:\DevCon\USB_Disk_Eject /removeletter $USBDriveLetter"       
        }
    }
    catch
    {
        # Catch the error, log it somewhere, but make sure you still eject the drive using below
        Start-Sleep -Seconds 60
        Invoke-Expression "c:\DevCon\USB_Disk_Eject /removeletter $USBDriveLetter"
    }
    
    Send-MailMessage -Subject $Subject -From $From -To $To -Body $body -SmtpServer $SMTPServer 
    
    write-output "------------------------------------Script end------------------------------------"

    Saturday, March 31, 2018 2:30 PM
  • What do you mean by "scheduled task fails"?  Are you asking how to detect when the script fails?

    I suspect you didn't write this script as it already has error detection built in.  It logs an error when it fails. 

    "Start-Sleep" is pointless in this script. There is nothing to wait for.


    \_(ツ)_/

    Saturday, March 31, 2018 2:33 PM
  • The script you have posted will not work because RoboCopy does not throw exceptions that can be caught.

    To detect errors with system utility programs you need to check the $LASTEXITCODE variable for the error exit of the program.


    \_(ツ)_/

    Saturday, March 31, 2018 2:38 PM
  • You are correct about me not writing it. I'm simply trying to build around it with some help from the community. I'm planning on running the script daily using Windows task scheduler. 

    I would like for it to send an e-mail if the Windows task scheduler fails for some reason. The challenge is that I don't want to rely on the built-in event id's for the scheduled task because I would then receive an email for all/any other tasks. This is why I was trying to include some logic to create a unique event id for this task and alert using that. 


    Saturday, March 31, 2018 2:52 PM
  • The script is not any good.  It will not work because RC cannot be trapped like that.

    You need to write a script that works and handles the errors correctly.


    \_(ツ)_/

    Saturday, March 31, 2018 2:53 PM
  • Understood but was hoping for some assistance in either someone providing a better script or helping me modify this one. Thanks anyways...
    Saturday, March 31, 2018 2:57 PM
  • I gave you guidance.  You need to use the exit code to check if the command worked.

    This forum des not provide scripts and it does not write or modify scripts you have found. You need to start by learning how to write a script or you won't even understand the guidance.

    If you want a script written for you then post here: Script requests


    \_(ツ)_/

    Saturday, March 31, 2018 3:30 PM
  • Thanks again.
    Saturday, March 31, 2018 3:45 PM