这是一个类似的问题
how-to-compress-log-files-older-than-30-days-in-windows
.
这个
ArchiveOldLogs.ps1
脚本将保留文件夹结构,无需中间复制。
你可以改变主意
-Filter
按名称而不是日期排除某些文件的参数:
$filter = {($_.Name -notlike '*.vs') -and ($_.Name -notlike '*.suo') -and ($_.Name -notlike '*.user') -and ($_.FullName -notlike '*bin\*') -and ($_.FullName -notlike '*obj\*')}
.\ArchiveOldLogs.ps1 -FileSpecs @('*.*') -Filter $filter -DeleteAfterArchiving:$false
下面是一个简单的示例,它不包括精美的进度条,不防止存档中出现重复,也不删除存档文件:
$ParentFolder = 'C:\projects\Code\' #files will be stored with a path relative to this folder
$ZipPath = 'c:\temp\projects.zip' #the zip file should not be under $ParentFolder or an exception will be raised
$filter = {($_.Name -notlike '*.vs') -and ($_.Name -notlike '*.suo') -and ($_.Name -notlike '*.user') -and ($_.FullName -notlike '*bin\*') -and ($_.FullName -notlike '*obj\*')}
@( 'System.IO.Compression','System.IO.Compression.FileSystem') | % { [void][Reflection.Assembly]::LoadWithPartialName($_) }
Push-Location $ParentFolder #change to the parent folder so we can get $RelativePath
$FileList = (Get-ChildItem '*.*' -File -Recurse | Where-Object $Filter) #use the -File argument because empty folders can't be stored
Try{
$WriteArchive = [IO.Compression.ZipFile]::Open( $ZipPath,'Update')
ForEach ($File in $FileList){
$RelativePath = (Resolve-Path -LiteralPath "$($File.FullName)" -Relative) -replace '^.\\' #trim leading .\ from path
Try{
[IO.Compression.ZipFileExtensions]::CreateEntryFromFile($WriteArchive, $File.FullName, $RelativePath, 'Optimal').FullName
}Catch{ #Single file failed - usually inaccessible or in use
Write-Warning "$($File.FullName) could not be archived. `n $($_.Exception.Message)"
}
}
}Catch [Exception]{ #failure to open the zip file
Write-Error $_.Exception
}Finally{
$WriteArchive.Dispose() #always close the zip file so it can be read later
}
Pop-Location