我面临一个如何将文件夹添加到现有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
注意,我也尝试允许脚本,我正在使用管理员权限启动。