PowerShell脚本,用于将所有旧文件归档到基于月份的目录中

q3qa4bjr  于 2023-01-02  发布在  Shell
关注(0)|答案(4)|浏览(184)

使用PowerShell,我得到了一个要求,从过去7年的所有历史文件存档压缩的基础上,月和年的创建日期和压缩后删除文件。
实现解决方案后,我应该看到如下所示的文件示例:

FolderName_2013-Jan.zip
FOlderName_2013-Feb.zip
FOlderName_2013-Mar.zip
FOlderName_2013-Jan.zip
FOlderName_2017-Jan.zip
FOlderName_2017-Dec.zip

我已经找到了几篇文章,但他们缺乏信息,以动态地通过每月月初和月底(例如:2013年1月1日至2013年1月31日或2015年6月1日至2015年6月30日),以过滤2013年以后所有月份的文件。
任何帮助都将不胜感激。

pjngdqdw

pjngdqdw1#

到目前为止,您是否尝试过任何操作?请按照以下步骤操作...

  • 使用Get-ChildItemSelect-Object -Unique获取唯一的创建日期
  • 获取所有文件并将其存储在变量中
  • ForEach使用Where-Object日期筛选文件,并将其通过管道传输到Compress-Archive

尝试它在您的水平最好的,仍然不能弄清楚,然后参考这个gist

wljmcqd8

wljmcqd82#

function Compress-Files {
[CmdletBinding()]
[Alias()]
[OutputType([int])]
Param
(
    # Sourcepath
    [Parameter(Mandatory = $true, ValueFromPipelineByPropertyName = $true, Position = 0)]
    $SourcePath,

    # number of months to compress in past
    [Parameter(Mandatory = $false, ValueFromPipelineByPropertyName = $true, Position = 2)]
    $Months

)

#region variables
$FullPath = $SourcePath + '*.*'
<#
    $date = (get-date).ToString("yyyy-MM-dd")
    $yesterday = (get-date).AddDays(-1).ToString("yyyyMMdd")
    $lastmonth = (get-date).AddMonths(-1).ToString("yyyyMMdd")
    $lastyear = (get-date).AddYears(-1).ToString("yyyyMMdd")
#>
#endregion

#region Compress months
#Compress files based on months in the past.
$Months = '-' + $Months
$Month = (get-date).AddMonths($Month).ToString("yyyyMMdd")

#$files = Get-ChildItem $FullPath | ? {$_.CreationTime -ge $Months -and $_.CreationTime -le $lastmonth}
#$files = Get-ChildItem $FullPath | ? {$_.CreationTime.ToString("yyyyMMdd") -ge $Months -and $_.CreationTime.ToString("yyyyMMdd") -le $lastmonth}

$files = Get-ChildItem -Path $FullPath | ? { $_.LastWriteTime.ToString("yyyyMMdd") -le $Month -and $_.Name -notlike "*.zip" -and $_.Mode -notlike "d*" }


foreach ($file in $files) {
    $filename = ($file.LastWriteTime).ToString("yyyy-MM")
    $DestinationPath = $SourcePath + $filename + '.zip'
    $file | Compress-Archive -DestinationPath $DestinationPath -update  
    Remove-Item $file -Force
    #if ($delete){ }

    ###Move Archiving logs to a text file
    "$DestinationPath|$file " | Out-File  "C:\temp\ExtractsArchive\Archivelog.txt" -Append
}
#>

}

#####Finally use the function on each and every sub directory

$根文件目录=“C:\临时\提取存档\”
$目录=获取子项路径$根文件目录递归目录|选择全名
ForEach($个目录中的$个目录){

$SourcePath = $Directory.FullName.ToString() + "\"

#$SourcePath.GetType()

Compress-Files -SourcePath  $SourcePath -Months 2

}

aiqt4smr

aiqt4smr3#

使用上面Kiran建议的Get-ChildItem命令,您可以生成FileInfo和DirectoryInfo对象。每个对象都有文件和/或目录的时间戳,存储在不同的属性中,如LastWriteTimeLastAccessTimeCreationTime。每个属性都包含[DateTime]类型的数据。一旦您为每个文件/文件夹都有了[DateTime]项,你可以这样做:

#Set variable $MY to be 7 years ago
$Now = (Get-Date)
$MY = $Now.AddYears(-7)

#Write custom Get-ChildItem statements to put list of files/folders in $AllItems variable

#Now, loop through with each month/year
Do
    #Filter $AllItems for the proper Month-Year
    $ThisMonthsItems = $AllItems.Where({$_.LastWriteTime.Month -eq $MY.Month -and $_.LastWriteTime.Year -eq $MY.Year})

    #Use $ThisMonthsItems to add items to your .zip file
    #This step left for you to fill with your compression routines

    $MY = $MY.AddMonths(1)
Loop Until ($MY.Month -eq $Now.Month -and $MY.Year -eq $Now.Year)

您可能需要调整循环以获得正确的时间窗口,但基本思想应该在那里为您。
祝你好运

bweufnob

bweufnob4#

我使用下面的脚本来删除旧文件和超过给定日期的zip文件。
在我的情况下,我希望删除超过3个月的归档文件。
我每个月运行一次,在月初,只保存最近3个月的文件,到下个月,最旧的一个月的文件就被删除了。
注意,在我的脚本中,我删除了旧的*.gz文件,但是压缩(归档)了旧的XML文件。

$datestamp = (Get-Date).toString("yyyy-MM-dd HH:mm:ss")

$server = "\\myserveraddress\"

$Path1 = $server + "c$\filelocation\files"

$Monthsback = -3    #keep 3 month's worth of files only, but check every month (so 1 month will drop off!)
$CurrentDate = Get-Date
$DatetoDelete = $CurrentDate.Date.AddMonths($Monthsback).ToString("yyyyMMdd")

try {
    write-host "$datestamp [info] Started"
    write-host "$datestamp [info] Cut off date: " $DatetoDelete

    #delete old files
    write-host "$datestamp [info] Removing files ..."
    Get-ChildItem $Path1 *.gz | Where-Object{ $_.LastWriteTime.ToString("yyyyMMdd") -lt $DatetoDelete } | Remove-Item

    # delete any previous copies of tmp.zip
    if (Test-Path ".\tmp.zip") { Remove-Item ".\tmp.zip" }

    # file all files and compress them into tmp.zip
    write-host "$datestamp [info] Compress and archive all old XML files ..."
    Get-ChildItem -Path $Path1 *.xml | Where-Object { $_.LastWriteTime.ToString("yyyyMMdd") -lt $DatetoDelete } | Compress-Archive -DestinationPath .\tmp.zip

    # if zip created...
    if (Test-Path ".\tmp.zip") { 
        write-host "$datestamp [info] Rename ZIP archive file ..."
        $filePath = ".\tmp.zip";
        $directory = [System.IO.Path]::GetDirectoryName($filePath);
        $strippedFileName = [System.IO.Path]::GetFileNameWithoutExtension($filePath);
        $extension = [System.IO.Path]::GetExtension($filePath);
        $newFileName = [DateTime]::Now.ToString("yyyyMMddHHmm") + "_XMLfiles" + $extension;
        $newFilePath = [System.IO.Path]::Combine($directory, $newFileName);
        Move-Item -LiteralPath $filePath -Destination $newFilePath;
        
        write-host "$datestamp [info] Remove old XML files ..."
        Get-ChildItem $Path1 *.xml | Where-Object { $_.LastWriteTime.ToString("yyyyMMdd") -lt $DatetoDelete } | Remove-Item
    }
}

catch {
    $message = $_
    Write-Warning "$datestamp [error] $message"
}

finally {
    write-host "$datestamp [info] FINISHED"
}

相关问题