2016-02-09 151 views
-1

我在Windows PowerShell中運行一個程序,其中列出了30天前修改過的文件的名稱。我需要以zip格式壓縮這些文件。代碼應該是什麼?如何使用PowerShell壓縮文件夾

#List all the folders in G:\logfiles 
$folders = (Get-ChildItem -Path "G:\logfiles" | Where-Object {$_.Attributes -eq "Directory"} | Select Fullname) 
#looping all folders 
Foreach ($folder in $folders) 
{ 
    $files = Get-ChildItem G:\logfiles\$folder | Where{$_.LastWriteTime -lt (Get-Date).AddDays(-30) 
} 
Foreach ($file in $files) 
{ 
    Move-Item $file G:\logfiles\$folder\$N  # *To move files to a folder name $N* 
} 
+0

有一個在你的邏輯存在缺陷。您的第一個for循環將每次覆蓋'$ files'。那只是一個錯字嗎? – Nkosi

回答

1

我會向您推薦powershell 5.0和新Compress-Archive cmdlet的

Compress-Archive -DestinationPath $folderToZip 
+0

嘿亞歷克西斯,我想壓縮所有30天的文件,但無法找到方法。在腳本中應該添加的內容 Foreach($文件夾中的$文件夾) { $ files = Get-ChildItem -Path G:\ logfiles \ $ folder |其中{$ _。LastWriteTime -lt(獲取最新).AddDays(-30) } 的foreach($文件$文件) { 布展項目$文件G:\日誌文件\ $文件夾\名稱 } – CodeX

+0

所以你有一個文件列表,並將它們移動到一個新的目錄。 所有似乎還剩下要做的就是使用compress-archive -DestinationPath G:\ logfiles \ $ folder \ $ N來壓縮新目錄 –

0

隨着降功能則可以壓縮文件。

function zipFile($Source ,$DestZip){ 
$folder = Get-Item -Path $Source 
$ZipFileName = $DestZip + ".zip" 

set-content $ZipFileName ("PK" + [char]5 + [char]6 + ("$([char]0)" * 18)) 

# Wait for the zip file to be created. 
while (!(Test-Path -PathType leaf -Path $ZipFileName)) 
{ 
    Start-Sleep -Milliseconds 20 
} 

$ZipFile = (new-object -com shell.application).NameSpace($ZipFileName) 

#BACKUP - COPY 
$ZipFile.CopyHere($Source) 

Write-Host "#Created zip file :" $DestZip 

}