如何使用PowerShell压缩文件夹

时间:2016-02-09 11:00:12

标签: powershell

我在windows powershell中运行一个程序,该程序列出了在30天之前修改过的文件名。我需要以zip格式压缩这些文件。应该是什么代码?

#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*
}

2 个答案:

答案 0 :(得分:1)

我会将您推荐给powershell 5.0和新的Compress-Archive cmdlet

Compress-Archive -DestinationPath $folderToZip

答案 1 :(得分: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

}