创建powershell脚本以备份文件并追加日期

创建powershell脚本以备份文件并追加日期,powershell,cmdlet,Powershell,Cmdlet,目前,我有一个单行批处理文件来备份文件。我需要备份文件时手动运行它。我唯一想补充的是当前日期。以下是我所拥有的: xcopy/W/Y ACTIVE.DB ACTIVE.DB.BACKUP 目标文件应该是ACTIVE.DB.BACKUP.YYYYMMDD。如何创建一个脚本,使我能够在Windows资源管理器中双击它并进行xcopy?您可以通过在PowerShell中的文件名中嵌入格式化的[datetime]::now来自定义文件名,如下所示: xcopy /W /Y ACTIVE.DB "ACTI

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

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


目标文件应该是ACTIVE.DB.BACKUP.YYYYMMDD。如何创建一个脚本,使我能够在Windows资源管理器中双击它并进行xcopy?

您可以通过在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-Location $path
Copy-Item ACTIVE.DB "ACTIVE.DB.$(get-date -f yyyyMMdd)" -Force -Confirm

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

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

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

  • 最后7天
  • 4周(每周五)
  • 6个月(每月最后一个星期五)
  • 4个季度(季度的最后一个月)
  • 2年(一年的最后一个季度)
它每天按计划任务运行,将ZIP放入目标文件夹,该文件夹也是Microsoft OneDrive的本地文件夹,因此ZIP也将远程同步到OneDrive服务器。那些过期的(非星期五每日或非最后一次DWMQY)拉链将被移动到非远程同步文件夹

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

  • 7天:160304-160229-160227
  • 4周:160304、160226、160219160212
  • 6个月:160226160129161225151127151025150925
  • 4个季度:15122515092515066062150327
  • 2年:151225141226
因此将有23个ZIP(实际上比DWMQY中的DUP少),我们的文件是250个文本文档,压缩后为0.4 GB,因此总共为23*0.4=9.2 GB,这比OneDrive免费的15 GB配额要少

对于大型源数据,可以使用7-zip,它提供最大16 mil 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)
    }    
}

#注意:有以下路径:
# 1. 源路径:要备份的路径。
# 2. 目标路径:存储在的当前ZIP,也是远程同步对的本地路径。
# 3. 移动到路径:要在此不可同步位置移动的过期拉链。
# 4. 临时路径:将源文件复制到中,以避免zip.exe在被其他进程占用时无法压缩它们。
#函数声明
. C:\Source\zipSaveDated\Functions.ps1
#压缩数据
$sourcePath='\\remoteMachine1\c$\SourceDocs\*'
$TempStorage='C:\Source\TempStorage'
$enddate=(获取日期).tostring(“yyyyymmdd”)
$zipFilename='\\remoteMachine2\d$\DailyBackupRemote\OneDrive\DailyBackupRemote\u OneDrive\'+$enddate+'\u CompanyDoc.zip'
删除项($TempStorage+'\*')-recurse-Force
复制项$sourcePath$TempStorage-recurse-Force
添加类型-A System.IO.Compression.FileSystem
[IO.Compression.ZipFile]::CreateFromDirectory($TempStorage,$zipFilename)
#移动旧文件
$SourceDir=“\\remoteMachine2\d$\DailyBackupRemote\OneDrive\DailyBackupRemote\u OneDrive”
$DestinationDir=“\\remoteMachine2\d$\DailyBackupRemote\bak”#存储从工作文件夹(OneDrive)移出的文件
$KeepDays=7
$KeepWeeks=4
$KeepMonths=6
$KeepQuarters=4
$KeepYears=2
#:循环文件
$Directory=$DestinationDir
if(!(测试路径$Directory))
{
新项$directory-type directory-Force
}
$files=获取子项$SourceDir**
foreach($files中的文件)
{#L1
#每日删除不会删除每周副本,7
如果($file.LastWriteTime-lt(Get Date).adddays(-$KeepDays).Date`
-和$file.LastWriteTime.DayOfWeek-与“星期五”不匹配`
)
{
移动项目$file.fullname$目录-强制
}
}#L1>>
$files=获取子项$SourceDir**
foreach($files中的文件)
{#L1
#每周删除不会删除每月的副本,4
如果($file.LastWriteTime-lt(Get Date).adddays(-$KeepWeeks*7).Date)`
-和(获取LastFridayOfMonth($file.LastWriteTime)).Date.ToString(“yyyyymmdd”)-不匹配$file.LastWriteTime.Date.ToString(“yyyyymmdd”)
)
{
移动项目$file.fullname$目录-强制
}
}#L1>>
$files=获取子项$SourceDir**
foreach($files中的文件)
{#L1
#每月删除不会删除季度副本,6
如果($file.LastWriteTime.Month-lt((获取日期).Year-$file.LastWriteTime.Year)*12+(获取日期).Month-$KeepMonths`
-和$file.LastWriteTime.Month-不在3、6、9、12
)
{
移动项目$file.fullname$目录-强制
}
}#L1>>
$files=获取子项$SourceDir**
foreach($files中的文件)
{#L1
#每季度删除不会删除年度副本,4
如果($file.LastWriteTime.Month-lt((获取日期).Year-$file.LastWriteTime.Year)*12+(获取日期).Month-$KeepQuarters*3`
-和$file.LastWriteTime.Month-不在12
)
{
移动项目$file.fullname$目录-强制
}
}#L1>>
$files=获取子项$SourceDir**
foreach($files中的文件)
{#L1
#每年一次的搬迁将一直进行下去
如果($file.LastWriteTime.Year-lt(获取日期).Year-$KeepYears)
{
移动项目$file.fullname$目录-强制
}
}#L1>>
函数Get-TimesResult3
{
参数([int]$a[int]$b)
$c=$a*$b
写入输出$c
}
函数获取工作日{
param(
$Month=$(获取日期-格式为'MM'),
$Year=$(获取日期-格式为'yyyy'),
$Days=1..5
)
$MaxDays=[Sy