在powershell V4中按日期归档文件夹组

时间:2016-09-25 14:45:48

标签: powershell

我希望将文件存档在超过X天数的路径中。我有一个包含多年文件的文件夹,最终目标是根据飞蛾存档项目。所以我每个月都有一个文件夹。

$SourcePath = "C:\users\StackoverFlow\Downloads"

$maxdays ="-30"

$CurrentDate = Get-Date

$ArchiveDate = $CurrentDate.AddDays($maxdays)

$destination = "C:\users\StackoverFlow\Desktop\Downloads.Zip"

$groups = Get-ChildItem $SourcePath | 
    Where-Object { ($_.LastWriteTime -lt $ArchiveDate) -and ($_.psIsContainer -eq $false) } | 
    group {"'{0}\{1}\{2:D2}'" -f $_.CreationTime}

ForEach ($group in $groups) {
    ForEach($file in $group.Group){
       Add-Type -assembly "system.io.compression.filesystem"
     [io.compression.zipfile]::CreateFromDirectory($SourcePath, $destination) 
    }
}

我希望RegEx会这样做,但它似乎没有做任何事情......

连连呢?

1 个答案:

答案 0 :(得分:2)

如果要按月和年分组,请确保您的格式字符串仅代表这些值。

-f运算符支持标准日期时间格式,因此您可以执行以下操作:

Group-Object {"{0:MMyyyy}" -f $_.CreationTime}

要将分组文件压缩到单个档案中,您必须先将它们移动到单个文件夹中:

Add-Type -assembly "system.io.compression.filesystem"

$SourcePath = "C:\users\StackoverFlow\Downloads"
$destination = "C:\users\StackoverFlow\Desktop\{0}"

$maxdays = -30
$CurrentDate = Get-Date

$ArchiveDate = $CurrentDate.AddDays($maxdays)

$groups = Get-ChildItem $SourcePath | 
    Where-Object { ($_.LastWriteTime -lt $ArchiveDate) -and ($_.psIsContainer -eq $false) } | 
    Group-Object { "{0:MMyyyy}" -f $_.CreationTime }

# Create a temporary working dir
$TmpDirPath = Join-Path $([System.IO.Path]::GetTempPath()) $([System.IO.Path]::GetRandomFileName())
$TmpDirectory = New-Item -Path $TmpDirPath -ItemType Directory 

ForEach ($group in $groups) {
    # Create a new directory for the group
    $GroupDirectory = New-Item -Path (Join-Path $TmpDirectory.FullName -ChildPath $group.Name) -ItemType Directory
    # Move files into the new directory
    $group.Group | Move-Item -Destination $GroupDirectory.FullName

    # Create the month-specific archive
    [System.IO.Compression.ZipFile]::CreateFromDirectory($GroupDirectory.FullName, ($destination -f $group.Name)) 
}

这将每月创建一个Zip档案 如果您想将它全部放在一个zip文件中,请将CreateFromDirectory调用移到循环外部并定位我们创建的顶级临时目录:

$destination = "C:\users\StackoverFlow\Desktop\Downloads.zip"
# ...
foreach ($group in $groups) {
    # Create a new directory for the group
    $GroupDirectory = New-Item -Path (Join-Path $TmpDirectory.FullName -ChildPath $group.Name) -ItemType Directory
    # Move files into the new directory
    $group.Group | Move-Item -Destination $GroupDirectory.FullName

}
[System.IO.Compression.ZipFile]::CreateFromDirectory($TmpDirectory.FullName, $destination)