Powershell - 根据另一个 zip 文件的内容压缩文件

Powershell - Compress files based on the contents of another zip file

我有一个 zip 文件,必须将其解压缩到目标文件夹。在我提取之前,我想备份 ONLY 根文件和将通过提取 zip 文件替换的子目录。

我可以编写一个脚本来找出 .zip 中的子目录并从目标文件夹中备份它们(如果它们可用)吗?

我将在 Azure DevOps 中使用这个脚本。

最简单的方法是将文件从 zip 文件提取到某个临时文件夹(在 Azure DevOps 上,它可能是此变量后面的文件夹 Agent.TempDirectory)。然后你可以将你想要备份的文件复制到另一个位置,比如$(Agent.TempDirectory)/backup,然后打包这个文件夹,如果你想发布它们,就把它们放在Build.ArtifactStagingDirectory中。在此之后,您可以再次将 zip 解压缩到您的目的地,因为您已经有了备份。

如果您想了解有关上述文件夹的更多信息,您可能会发现此 documentation 很有用。

您可以使用 PowerShell 来发现 zip 文件内容,检查它是否存在于目标文件夹中,如果存在 - 进行备份。例如:

$ZipFilePath = "C:\Users\sabramczyk\Documents\Scrum.zip"
$DestinationFolder = "c:\test"

Add-Type -assembly "System.IO.Compression.FileSystem"
    
if (![System.IO.File]::Exists($ZipFilePath)) {
    throw "Zip file ""$ZipFilePath"" not found."
}

$ZipContent = ([System.IO.Compression.ZipFile]::OpenRead($ZipFilePath)).Entries.FullName
foreach($zipContent in $ZipContent)
{
    if(Test-Path $DestinationFolder+"/"+$zipContent)
    {
        # Do backup
    }
}