Prasad123
Prasad123

Reputation: 11

Powershell Script to archive as zip files based on file name

I am new to powershell, could you please help me in powershell script to archive as zip files based on file name and destination file name should use file created date. Please find the sample scenario for the same.

Source Folder : (C:\documents\dailyfiles)

A0001.dat created date : 2014-10-01
B0001.dat created date : 2014-10-01
C0001.dat created date : 2014-10-01
D0001.dat created date : 2014-10-01
A0002.dat created date : 2014-10-02
B0002.dat created date : 2014-10-02
C0002.dat created date : 2014-10-02
D0002.dat created date : 2014-10-02
A0003.dat created date : 2014-10-03
B0003.dat created date : 2014-10-03
C0003.dat created date : 2014-10-03
D0003.dat created date : 2014-10-03
.
.
.
A0010.dat created date : 2014-10-10
B0010.dat created date : 2014-10-10
C0010.dat created date : 2014-10-10
D0010.dat created date : 2014-10-10

Destination Folder (C:\documents\Archive)

Arch_0001_20141001.zip
Arch_0002_20141002.zip
Arch_0003_20141003.zip
.
.
.
Arch_0010_20141010.zip

Each zip file will have A,B,C and D.dat file. Thanks a lot in advance for your help.

Thanks, Prasad.

Upvotes: 0

Views: 2034

Answers (1)

hysh_00
hysh_00

Reputation: 839

Please give this a try. (You will need PowerShell 3.0.)

$SFOLDER= "C:\temp"
$DSTFOLDER="C:\temp2"

[System.Reflection.Assembly]::LoadWithPartialName('System.IO.Compression.FileSystem')
[System.Type]$typeAcceleratorsType=[System.Management.Automation.PSObject].Assembly.GetType('System.Management.Automation.TypeAccelerators',$true,$true)

$TMP=@()
Get-ChildItem $SFOLDER |%{
$TMP += New-Object -TypeName PSCustomObject -Property @{'Name' = $_.name
                                                       'Date' = (get-date($_.CreationTime) -Format "yyyy-MM-dd")}
}

$TMP|Group-Object DATE|%{
   New-Item -path $DSTFOLDER -name $_.Group[0].Date  -itemtype directory ;
   foreach($i in $_.Group){
           Copy-item  ($SFOLDER+"\"+$i.Name)  ($DSTFOLDER+"\"+$_.Group[0].Date)
       }
   [System.IO.Compression.Zipfile]::CreateFromDirectory( ($DSTFOLDER+"\"+$_.Group[0].Date),($DSTFOLDER+"\"+$_.Group[0].Date+".zip"))
   Remove-Item -Recurse ($DSTFOLDER+"\"+$_.Group[0].Date)
}

Upvotes: 1

Related Questions