创建PowerShell脚本以备份文件并附加日期

时间:2010-09-08 20:35:08

标签: powershell cmdlet

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

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

目标文件应该只是ACTIVE.DB.BACKUP.YYYYMMDD。我将如何创建一个脚本,允许我从Windows资源管理器中双击它并使xcopy发生?

3 个答案:

答案 0 :(得分:8)

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

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

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

答案 1 :(得分:4)

您可以通过在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 :(得分:0)

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

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

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

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

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

  • 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个拉链(实际上自DWMQY中的重复以来更少),我们的文件是250个文本文档,在压缩后为0.4 GB,因此它的总数为23 * 0.4 = 9.2 GB比OneDrive免费15 GB配额。

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

# 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)
    }    
}