创建 powershell 脚本来备份文件并附加日期

发布于 2024-09-17 21:56:11 字数 199 浏览 9 评论 0原文

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

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

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

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

闻呓 2024-09-24 21:56:11

只是要指出,您可以使用 Copy-Item 来做到这一点,例如:

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

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

Just to point out that you can do this with Copy-Item e.g.:

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

If you're going for robust then I'd use robocopy.exe.

风吹雨成花 2024-09-24 21:56:11

您可以通过在 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 命令的批处理文件,如下所述:

设置PowerShell脚本以自动执行

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

一场春暖 2024-09-24 21:56:11

我本月刚刚在 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、1 51025, 150925
  • 4 quarters: 151225, 150925,150626,150327
  • 2years: 151225, 141226

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

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

I just made a Daily/Weekly/Monthly/Quarterly/Yearly backup script in Powershell this month, and hope it helps.

This DWMQY backup scenario is to zip a source folder to a date-named zip file, then keep the zips of:

  • last 7 days
  • 4 weeks (each Friday's)
  • 6 months (the last Friday's of each month)
  • 4 quarters (the last month's of quarter)
  • 2 years (the last quarter's of year).

Running as scheduled task on daily basis, it puts the zips into a target folder which is also a Microsoft OneDrive's local folder, so the zips also being remotely sync'd to OneDrive server. Those outdated (non-Friday daily or non-last-DWMQY) zips will be moved to a non-remotely-sync'd folder.

It's March 5, 2016 today, the following zips should be in the target folder:

  • 7 days: 160304-160229-160227
  • 4 weeks: 160304, 160226, 160219,160212
  • 6 months: 160226, 160129, 161225, 151127, 151025, 150925
  • 4 quarters: 151225, 150925,150626,150327
  • 2 years: 151225, 141226

So there will be 23 zips (actually less since the dups among DWMQY), our files are 250 text documents which is 0.4 GB after zipping, so it's 23*0.4 = 9.2 GB in total, which is less than OneDrive free 15 GB quota.

For large source data, 7-zip can be used, which provides maximum 16 mil TB zip size. For directly backup folders instead of zips, haven't tried. Guessing it's a transferable procedure from the current zip way.

# 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)
    }    
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文