Powershell脚本根据文件名归档为zip文件

时间:2014-10-08 05:55:52

标签: powershell

我是PowerShell的新手,你能帮我在powershell脚本中存档,因为基于文件名和目标文件名的zip文件应该使用文件创建日期。    请找到相同的示例场景。

源文件夹:(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

目标文件夹(C:\ documents \ Archive)

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

每个zip文件都有A,B,C和D.dat文件。非常感谢您的帮助。

谢谢, 普拉萨德。

1 个答案:

答案 0 :(得分:1)

请试一试。 (您将需要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)
}