ファイルをバックアップして日付を追加するためにPowerShellスクリプトを作成する

StackOverflow https://stackoverflow.com/questions/3671657

  •  01-10-2019
  •  | 
  •  

質問

現在、ファイルをバックアップする1行バッチファイルがあります。ファイルをバックアップする必要があるときに手動で実行します。私がそれに追加したい唯一のことは、現在の日付です。これが私が持っているものです:

xcopy /w /y Active.db Active.db.backup

宛先ファイルは、単にActive.db.backup.yyyymmddである必要があります。 Windows ExplorerからダブルクリックしてXcopyを実現できるようにするスクリプトを作成するにはどうすればよいですか?

役に立ちましたか?

解決

フォーマットを埋め込むことにより、ファイル名をカスタマイズできます [datetime]::now PowerShellのファイル名で

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スクリプトをセットアップします

他のヒント

コピー項目でこれを行うことができることを指摘するために:

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

あなたが堅牢になるなら、私は使用します robocopy.exe.

今月、PowerShellで毎日/毎週/毎月/四半期/毎年のバックアップスクリプトを作成しましたが、それが役立つことを願っています。

このdwmqyバックアップシナリオは、ソースフォルダーを日付付けのzipファイルにzip zipにしてから、次のzipを保持することです。

  • 過去7日間
  • 4週間(毎週金曜日)
  • 6か月(毎月の最後の金曜日)
  • 4四半期(四半期の最後の月)
  • 2年(年の最後の四半期)。

スケジュールされたタスクとして毎日実行されているため、ZIPSをMicrosoft OneDriveのローカルフォルダーであるターゲットフォルダーに入れます。そのため、ZIPはOneDriveサーバーにリモートで同期されます。これらの時代遅れの(金曜日以外の毎日または非LAST-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のzipsがあります(実際にはDWMQYの間のDUP以降)、ファイルはジッピング後0.4 GBである250のテキストドキュメントであるため、合計23*0.4 = 9.2 GBで、OneDrive無料の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)
    }    
}
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top