代码之家  ›  专栏  ›  技术社区  ›  Alloue

将文件夹添加到zip

  •  0
  • Alloue  · 技术社区  · 7 年前

    我面临一个如何将文件夹添加到现有ZIP文件的问题。

    此zip文件也是由PowerShell创建的。

    我只能使用Powershell 5提供的系统类。我不能使用任何用户包或插件(包括7zip)。

    这是我的代码:

    function addFileToArchiveTest ($filePathToAdd, $archivePathToUpdate) {
        if ([System.IO.File]::Exists($filePathToAdd) -or (Test-Path $filePathToAdd)) {
            $file = [System.IO.Path]::GetFileName($filePathToAdd);
            Write-Host $filePathToAdd.Name;
            Write-Host $filePathToAdd;
            Write-Host $archivePathToUpdate;
            $archive = [System.IO.Compression.ZipFile]::Open($archivePathToUpdate, [System.IO.Compression.ZipArchiveMode]::Update);
            $compressionLevel = [System.IO.Compression.CompressionLevel]::NoCompression;
            [System.IO.Compression.ZipFileExtensions]::CreateEntryFromFile($archive, $filePathToAdd, $file, "$compressionLevel");
            $archive.Dispose();
        } else {
            Write-Host "[ERROR@function] <AddFileToArchive>: <filePathToAdd> does not exist!";
            Write-Host "[ERROR@function] <Variable<filePathToAdd>>: $filePathToAdd";
            Write-Host "[ERROR@function] <Variable<archivePathToUpdate>>: $archivePathToUpdate";
        }
    }
    

    我在考虑变量 $file -可能有问题,因为文件夹没有扩展名。

    我运行的脚本如下:

    PS> addFileToArchiveTest "C:\TestFolder\FolderToArchive" "C:\TestFolder\thereIsAlreadyZipFile.zip"
    

    返回时出错:

    Exception calling "CreateEntryFromFile" with "4" argument(s): "Access to the
    path 'C:\TestFolder\FolderToArchive' is denied."
    At C:\Users\user\Desktop\testfolder.ps1:196 char:13
    +             [System.IO.Compression.ZipFileExtensions]::CreateEntryFro ...
    +             ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
        + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
        + FullyQualifiedErrorId : UnauthorizedAccessException
    

    注意,我也尝试允许脚本,我正在使用管理员权限启动。

    2 回复  |  直到 7 年前
        1
  •  0
  •   Ansgar Wiechers    7 年前

    也许令人惊讶的是, CreateEntryFromFile() 用于添加 文件 文件夹 。您需要单独添加每个文件:

    Get-ChildItem $filePathToAdd | ForEach-Object {
        [IO.Compression.ZipFileExtensions]::CreateEntryFromFile($archive, $_.FullName, $_.Name, "$compressionLevel")
    }
    
        2
  •  0
  •   Alloue    7 年前

    用户@guiwhatssthat回答:PowerShell 5支持压缩存档。它正是你想要的。

    这正是我想要的。