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

使用Powershell将文件移动到1天以前的存档,powershell,Powershell,我只想自动化前一天的归档过程(包括压缩和删除)。我有一个每天都运行的脚本,用于归档,但我只能设置几天,只选择一天仍然是一个挑战 我设置了两个固定变量($archiveyear,$archivemonth,$archiveday),它们实际上允许我每天存档,但我需要每天手动更改 $ArchiveYear = "2018" $ArchiveMonth = "06" $ArchiveDay = "06" $SourcePath = "C:\aa\bb\x" $TargetPath = "C:\ab"

我只想自动化前一天的归档过程(包括压缩和删除)。我有一个每天都运行的脚本,用于归档,但我只能设置几天,只选择一天仍然是一个挑战

我设置了两个固定变量(
$archiveyear
$archivemonth
$archiveday
),它们实际上允许我每天存档,但我需要每天手动更改

$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
    } 
}

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

如果是:

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

[string]$ArchiveYear = $yesterday.Year
[string]$ArchiveMonth = $yesterday.Month
[string]$ArchiveDay = $yesterday.Day

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

如果是:

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

[string]$ArchiveYear = $yesterday.Year
[string]$ArchiveMonth = $yesterday.Month
[string]$ArchiveDay = $yesterday.Day

你到底有什么问题?你到底有什么问题?嗨,谢谢,你理解得对,在我测试这个之前,我还有一个问题?--$Days=“1”这可以保持这样吗?“将早于$Days的文件从$SourcePath移动到$TargetFolder”现在将被否决$昨天=(Get Date).AddDays(-1),只捕获昨天的文件。或者我需要删除此规则吗?关于,RChouse edit-将
$Days
移到顶部,新代码也可以使用它。您好,谢谢,您理解正确,在我测试此规则之前,我还有一个问题?--$Days=“1”这可以保持这样吗?“将早于$Days的文件从$SourcePath移动到$TargetFolder”现在将被否决$昨天=(Get Date).AddDays(-1),只捕获昨天的文件。或者我是否需要删除此规则,rchouse edit-将
$Days
移到顶部,新代码也可以使用它。