la creazione di script di PowerShell per il backup di un file e aggiungere la data

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

  •  01-10-2019
  •  | 
  •  

Domanda

Attualmente ho un file batch una riga per eseguire il backup di un file. Ho eseguito manualmente quando ho bisogno di eseguire il backup di un file. L'unica cosa che vorrei aggiungere ad essa è la data corrente. Ecco quello che ho:

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

il file di destinazione dovrebbe essere semplicemente ACTIVE.DB.BACKUP.YYYYMMDD. Come potrei fare per la creazione di uno script che mi permetterà di fare doppio clic su di esso da Esplora risorse di Windows e rendere il Xcopy accada?

È stato utile?

Soluzione

È possibile personalizzare il nome del file, grazie all'integrazione di un [datetime]::now formattato nel nome del file in PowerShell in questo modo:

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

Se la linea si sente impegnato e impossibile da mantenere, è possibile refactoring a più linee:

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

Per ottenere l'esecuzione del doppio clic, di solito faccio un file batch che esegue il comando di PowerShell, come descritto qui:

Set up PowerShell script per l'esecuzione automatica

Altri suggerimenti

Giusto per sottolineare che si può fare questo con copia-Item per esempio:.

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

Se si sta andando per robusta poi userei robocopy.exe.

Ho appena fatto uno script giornaliero / settimanale / mensile / trimestrale / annuale di backup in PowerShell questo mese, e spero che aiuta.

Questo scenario di backup DWMQY è quello di comprimere una cartella di origine in un file zip data nome, poi tenere le cerniere di:

  • ultimi 7 giorni
  • 4 settimane (ogni Venerdì)
  • 6 mesi (l'ultimo del mese, di ogni Venerdì)
  • 4 trimestri (l'ultimo mese è del trimestre)
  • 2 anni (l'ultimo trimestre è dell'anno).

In esecuzione come operazione pianificata su base giornaliera, si mette le cerniere in una cartella di destinazione, che è anche la cartella locale di un Microsoft Microsoft Onedrive, quindi le cerniere anche in remoto sincronizzato al server Microsoft Onedrive. Quelli obsoleti (non-Venerdì giornaliera o non-last-DWMQY) cerniere verranno spostati in una cartella non in remoto sincronizzati.

E '5 marzo 2016 oggi, le seguenti cerniere dovrebbero essere nella cartella di destinazione:

  • 7 giorni: 160304-160229-160227
  • 4 settimane: 160304, 160226, 160219,160212
  • 6 mesi: 160226, 160129, 161225, 151127, 151025, 150925
  • 4 trimestri: 151225, 150925,150626,150327
  • 2 anni: 151225, 141226

Quindi ci saranno 23 cerniere (in realtà meno dal momento che i dups tra DWMQY), i nostri file sono 250 documenti di testo, che è 0,4 GB dopo zippare, quindi è 23 * 0,4 = 9,2 GB in totale, che è meno di Microsoft Onedrive free 15 contingente GB.

Per i dati sorgente grandi, 7-zip può essere utilizzato, che fornisce la massima dimensione 16 mil TB zip. Per le cartelle di backup direttamente invece di cerniere, non ho provato. Indovinando che è una procedura trasferibili dal modo in cui zip corrente.

# 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)
    }    
}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top