使用Powershell将文件移动到1天的存档

时间:2018-06-07 08:30:24

标签: powershell

我想要仅在前一天自动化存档过程(包括zip和删除)。我有一个每天运行的脚本,它可以存档但是我可以将它设置好几天,只挑选一天仍然是一个挑战。

我设置了几个固定变量($archiveyear$archivemonth$archiveday),这些变量实际上让我每天都会存档,但我需要每天手动更改。< / p>

$ArchiveYear = "2018"
$ArchiveMonth = "06"
$ArchiveDay = "06"

$SourcePath = "C:\aa\bb\x"
$TargetPath = "C:\ab"
$YourDirToCompress = "C:\aa\bb\$ArchiveYear\$ArchiveMonth\$ArchiveDay"
$ZipFileResult = "C:\TestDestination\$ArchiveDay$ArchiveMonth.zip"

Get-ChildItem $YourDirToCompress -Directory  | 
    #where { $_.Name -notin $DirToExclude} | 
Compress-Archive -DestinationPath $ZipFileResult -Update
$Days = "1"
$LogPath = "C:\Temp" 
$Date = Get-Date -format yyyy-MM-dd_HH-mm 
$TargetFolder = "$TargetPath\$Date"
$LogFile = "$LogPath\ArchiveLog-$date.txt"
$TargetZipFile = "$TargetPath\$Date.zip"

$Activity = "Move files older than $Days days from $SourcePath to $TargetFolder"
Write-Verbose $Activity

$OldFiles = Get-Childitem -Path $SourcePath -recurse | Where-Object {$_.LastWriteTime -lt (get-date).AddDays( - $days)} 
$Total = $Oldfiles.Count
$Current = 0
$OldFiles | ForEach { 
    $Current ++
    $Filename = $_.fullname 
    Write-Progress -Activity $Activity -Status $FileName -PercentComplete ($Current / $Total * 100)    
    $Split = $FileName -split '\\'
    $DestFile = $split[1..($split.Length - 1)] -join '\' 
    $DestFile = "$TargetFolder\$DestFile"

    Try { 
        $null = New-Item -Path  $DestFile -Type File -Force
        $Null = Move-Item -Path  $FileName -Destination $DestFile -Force -ErrorAction:SilentlyContinue 
        "Successfully moved $filename to $targetfolder" | add-content $LogFile 
    } 
    Catch { 
        $Err = $_.Exception.Message
        Write-Error $Err
        "Error moving $filename`: $Err " | add-content $LogFile
    } 
}

1 个答案:

答案 0 :(得分:2)

如果我理解了这个问题,您希望脚本计算昨天的日期,而不是每次运行\安排脚本时手动更新$ArchiveYear \ $ArchiveMonth \ $ArchiveDay

如果是这样的话:

$Days = "1"
$yesterday = (Get-Date).AddDays(-$Days)

[string]$ArchiveYear = $yesterday.Year
[string]$ArchiveMonth = $yesterday.Month
[string]$ArchiveDay = $yesterday.Day
相关问题