Search code examples
powershellpowershell-cmdlet

creating powershell script to backup a file and append the date


Currently I have a one line batch file to back up a file. I run it manually when I need to back up a file. The only thing I would like to add to it is the current date. Here is what I have:

xcopy /W /Y ACTIVE.DB ACTIVE.DB.BACKUP

the destination file should simply be ACTIVE.DB.BACKUP.YYYYMMDD. How would I go about creating a script that will allow me to double click on it from Windows Explorer and make the xcopy happen?


Solution

  • You can customize your filename by embedding a formatted [datetime]::now in the file name in PowerShell like so:

    xcopy /W /Y ACTIVE.DB "ACTIVE.DB.BACKUP.$([datetime]::now.ToString('yyyy-MM-dd'))"
    

    If the line feels busy and unmaintainable, you can refactor it to multiple lines:

    $now = [datetime]::now.ToString('yyyy-MM-dd')
    xcopy /W /Y ACTIVE.DB "ACTIVE.DB.BACKUP.$now"
    

    To get double-click execution, I usually make a batch file that runs the PowerShell command as described here:

    Set up PowerShell Script for Automatic Execution