Question:
I am trying to copy/move one text file to the zip. I don’t want to unzip it, copy the file and zip it back. Is there any way we can directly copy or move text file to the zip in powershell. When i am doing it in powershell, it’s doing after that when i try to look inside the zip it’s saying invalid path.
Powershell commands:
1 2 3 4 5 6 7 8 |
$A = "20160914.4" New-Item "C:\test\VersionLabel.txt" -ItemType file $A | Set-Content "C:\test\VersionLabel.txt" Copy-Item "C:\test\VersionLabel.txt" "C:\test\Abc.zip" -Force |
Error: The compressed folder is invalid
Answer:
>= PowerShell 5.0
Per @SonnyPuijk’s answer above, use Compress-Archive
.
1 2 3 4 5 |
clear-host [string]$zipFN = 'c:\temp\myZipFile.zip' [string]$fileToZip = 'c:\temp\myTestFile.dat' Compress-Archive -Path $fileToZip -Update -DestinationPath $zipFN |
< PowerShell 5.0
To add a single file to an existing zip:
1 2 3 4 5 6 7 8 9 10 |
clear-host Add-Type -assembly 'System.IO.Compression' Add-Type -assembly 'System.IO.Compression.FileSystem' [string]$zipFN = 'c:\temp\myZipFile.zip' [string]$fileToZip = 'c:\temp\myTestFile.dat' [System.IO.Compression.ZipArchive]$ZipFile = [System.IO.Compression.ZipFile]::Open($zipFN, ([System.IO.Compression.ZipArchiveMode]::Update)) [System.IO.Compression.ZipFileExtensions]::CreateEntryFromFile($ZipFile, $fileToZip, (Split-Path $fileToZip -Leaf)) $ZipFile.Dispose() |
To create a single file zip file from scratch:
Same as above, only replace: [System.IO.Compression.ZipArchiveMode]::Update
With: [System.IO.Compression.ZipArchiveMode]::Create
Related Documentation:
Compress-Archive
: https://technet.microsoft.com/en-us/library/dn841358.aspxCreateEntryFromFile
: https://msdn.microsoft.com/en-us/library/hh485720(v=vs.110).aspx