【问题标题】:creating powershell script to backup a file and append the date创建 powershell 脚本来备份文件并附加日期
【发布时间】:2011-04-09 22:57:39
【问题描述】:

目前我有一个单行批处理文件来备份文件。当我需要备份文件时,我会手动运行它。我唯一想添加的是当前日期。这是我所拥有的:

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

目标文件应该只是 ACTIVE.DB.BACKUP.YYYYMMDD。我将如何创建一个脚本,让我可以从 Windows 资源管理器中双击它并进行 xcopy?

【问题讨论】:

    标签: powershell cmdlet


    【解决方案1】:

    您可以通过在 PowerShell 中的文件名中嵌入格式化的 [datetime]::now 来自定义文件名,如下所示:

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

    如果感觉线路繁忙且无法维护,您可以将其重构为多行:

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

    为了获得双击执行,我通常制作一个运行 PowerShell 命令的批处理文件,如下所述:

    Set up PowerShell Script for Automatic Execution

    【讨论】:

      【解决方案2】:

      只是指出您可以使用 Copy-Item 执行此操作,例如:

      Set-Location $path
      Copy-Item ACTIVE.DB "ACTIVE.DB.$(get-date -f yyyyMMdd)" -Force -Confirm
      

      如果你想要健壮,那么我会使用robocopy.exe

      【讨论】:

        【解决方案3】:

        我本月刚刚在 Powershell 中制作了每日/每周/每月/每季度/每年的备份脚本,希望对您有所帮助。

        此 DWMQY 备份方案是将源文件夹压缩到以日期命名的 zip 文件,然后保留以下文件的 zip:

        • 过去 7 天
        • 4 周(每个星期五)
        • 6 个月(每个月的最后一个星期五)
        • 4 个季度(季度的最后一个月)
        • 2 年(一年的最后一个季度)。

        每天按计划任务运行,它将 zip 放入目标文件夹中,该文件夹也是 Microsoft OneDrive 的本地文件夹,因此 zip 也可以远程同步到 OneDrive 服务器。那些过时的(非星期五的每日或非最后的 DWMQY)zip 将被移动到非远程同步的文件夹中。

        今天是 2016 年 3 月 5 日,目标文件夹中应该有以下 zip:

        • 7天:160304-160229-160227
        • 4 周:160304、160226、160219、160212
        • 6个月:160226、160129、161225、151127、151025、150925
        • 4个季度:151225、150925、150626、150327
        • 2 年:151225、141226

        所以会有 23 个 zip(实际上比 DWMQY 中的 dup 少),我们的文件是 250 个文本文档,压缩后是 0.4 GB,所以总共是 23*0.4 = 9.2 GB,小于 OneDrive free 15 GB 配额。

        对于大型源数据,可以使用 7-zip,它提供最大 16 百万 TB 的 zip 大小。对于直接备份文件夹而不是 zip,还没有尝试过。猜测这是从当前 zip 方式转移的过程。

        # Note: there are following paths:
        # 1. source path: path to be backed up. 
        # 2. target path: current zips stored at, which is also a remote-sync pair's local path.
        # 3. moved-to path: outdated zips to be moved in this non-sync'able location.
        # 4. temp path: to copy the source file in to avoid zip.exe failing of compressing them if they are occupied by some other process.
        # Function declaration
        . C:\Source\zipSaveDated\Functions.ps1 
        # <1> Zip data
        $sourcePath = '\\remoteMachine1\c$\SourceDocs\*'
        $TempStorage = 'C:\Source\TempStorage'
        $enddate = (Get-Date).tostring("yyyyMMdd")
        $zipFilename = '\\remoteMachine2\d$\DailyBackupRemote\OneDrive\DailyBackupRemote_OneDrive\' + $enddate + '_CompanyDoc.zip'
        Remove-Item ($TempStorage + '\*') -recurse -Force
        Copy-Item $sourcePath $TempStorage -recurse -Force
        
        Add-Type -A System.IO.Compression.FileSystem
        [IO.Compression.ZipFile]::CreateFromDirectory($TempStorage, $zipFilename) 
        
        # <2> Move old files
        $SourceDir = "\\remoteMachine2\d$\DailyBackupRemote\OneDrive\DailyBackupRemote_OneDrive"
        $DestinationDir = "\\remoteMachine2\d$\DailyBackupRemote\bak" # to store files moved out of the working folder (OneDrive)
        $KeepDays = 7
        $KeepWeeks = 4
        $KeepMonths = 6
        $KeepQuarters = 4
        $KeepYears = 2
        # <2.1>: Loop files
        $Directory = $DestinationDir
        if (!(Test-Path $Directory))
        {
            New-Item $directory -type directory -Force
        }
        $files = get-childitem $SourceDir *.*
        foreach ($file in $files) 
        { # L1
            # daily removal will not remove weekly copy, 7 
            If($file.LastWriteTime -lt (Get-Date).adddays(-$KeepDays).date  `
                -and $file.LastWriteTime.DayOfWeek -NotMatch "Friday"  `
                )
                {
                Move-Item $file.fullname $Directory -force
                }
        } # L1 >>
        $files = get-childitem $SourceDir *.*
        foreach ($file in $files) 
        { # L1
            # weekly removal will not remove monthly copy, 4
            If($file.LastWriteTime -lt (Get-Date).adddays(-$KeepWeeks * 7).date  `
                -and (Get-LastFridayOfMonth ($file.LastWriteTime)).Date.ToString("yyyyMMdd") -NotMatch $file.LastWriteTime.Date.ToString("yyyyMMdd")
                )
                {
                Move-Item $file.fullname $Directory -force
                }
        } # L1 >>
        $files = get-childitem $SourceDir *.*
        foreach ($file in $files) 
        { # L1
            # monthly removal will not remove quarterly copy, 6
            If($file.LastWriteTime.Month -lt ((Get-Date).Year - $file.LastWriteTime.Year) * 12 + (Get-Date).Month - $KeepMonths `
                -and $file.LastWriteTime.Month -NotIn 3, 6, 9, 12
                )
                {
                Move-Item $file.fullname $Directory -force
                }
        } # L1 >>
        $files = get-childitem $SourceDir *.*
        foreach ($file in $files) 
        { # L1
            # quarterly removal will not remove yearly copy, 4
            If($file.LastWriteTime.Month -lt ( (Get-Date).Year - $file.LastWriteTime.Year) * 12 + (Get-Date).Month - $KeepQuarters * 3 `
                -and $file.LastWriteTime.Month -NotIn 12
                )
                {
                Move-Item $file.fullname $Directory -force
                }
        } # L1 >>
        $files = get-childitem $SourceDir *.*
        foreach ($file in $files) 
        { # L1
            # yearly removal will just go straight ahead. 2
            If($file.LastWriteTime.Year -lt (Get-Date).Year - $KeepYears )
                {
                Move-Item $file.fullname $Directory -force
                }
        } # L1 >>
        
        
        <Functions.ps1>
        function Get-TimesResult3 
            {
            Param ([int]$a,[int]$b)
            $c = $a * $b
            Write-Output $c
            }
        
        function Get-Weekday {
            param(
                $Month = $(Get-Date -format 'MM'),
                $Year = $(Get-Date -format 'yyyy'),
                $Days = 1..5
            )
        $MaxDays = [System.DateTime]::DaysInMonth($Year, $Month)
        1..$MaxDays | ForEach-Object {
                Get-Date -day $_ -Month $Month -Year $Year |
                  Where-Object { $Days -contains $_.DayOfWeek }  
            }
        }
        
        function Get-LastFridayOfMonth([DateTime] $d) {    
            $lastDay = new-object DateTime($d.Year, $d.Month, [DateTime]::DaysInMonth($d.Year, $d.Month))
            $diff = ([int] [DayOfWeek]::Friday) - ([int] $lastDay.DayOfWeek)
        
            if ($diff -ge 0) {
                return $lastDay.AddDays(- (7-$diff))
            }
            else {
                return $lastDay.AddDays($diff)
            }    
        }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2019-03-10
          • 2022-08-13
          • 1970-01-01
          • 2021-06-27
          • 1970-01-01
          • 1970-01-01
          • 2021-12-06
          相关资源
          最近更新 更多