Reputation: 755
I have a set of files named as: 20161205_abc, 20161205_bcd, 20161205_cde, 20161206_abc, 20161204_abc.
I have a script in place to zip all the files who have names like: 20161205*.
Add-Type -assembly 'System.IO.Compression'
[string]$zipFN = 'u:\users\riteshthakur\desktop\myZipFile.zip'
[string]$fileToZip = 'u:\users\riteshthakur\desktop\abc\20161205*.txt'
[System.IO.Compression.ZipArchive]$ZipFile = [System.IO.Compression.ZipFile]::Open($zipFN, ([System.IO.Compression.ZipArchiveMode]::Create))
[System.IO.Compression.ZipFileExtensions]::CreateEntryFromFile($ZipFile, $fileToZip, (Split-Path $fileToZip -Leaf))
$ZipFile.Dispose()
This throws error: "Exception calling "CreateEntryFromFile" with "3" argument(s): "Illegal characters in path." At U:\Users\riteshthakur\Desktop\Zip.PS1:7 char:1 + [System.IO.Compression.ZipFileExtensions]::CreateEntryFromFile($ZipFile, $fileTo ..."
Please help.
Upvotes: 2
Views: 3719
Reputation: 27423
I like to preserve the folder structure. You have to be in the directory above what you want to zip for this script to work.
# myzip.ps1
# example "ls -r foo | .\myzip foo.zip
# doesn't zip empty folders
Param([parameter(ValueFromPipeline=$True)]$file,
[parameter(position=0)]$zipfile)
Begin {
if (test-path $zipfile) {
'zipfile exists'
exit 1
}
Add-Type -AssemblyName 'system.io.compression.filesystem'
# update or create
$zip = [System.IO.Compression.ZipFile]::Open($zipfile,'create')
}
Process {
# "test-path $file pathtype leaf" doesn't work right
if ($file | test-path -pathtype leaf) {
$rel = $file | resolve-path -relative
$rel = $rel -replace '^\.\\','' # take .\ off front
$rel = $rel -replace '^\./','' # osx take ./ off front
# destination, sourcefilename, entryname, compressionlevel
[System.IO.Compression.ZipFileExtensions]::CreateEntryFromFile($zip,
$rel, $rel, 'optimal')
} elseif ($file | test-path -pathtype container) {
"$file is container"
} else {
"$file is unknown"
}
}
End {
$zip.dispose()
}
Upvotes: 0
Reputation: 17462
in powershell V5 you can simply do it like it:
$zipFN = 'u:\users\riteshthakur\desktop\myZipFile.zip'
$fileToZip = 'u:\users\riteshthakur\desktop\abc\20161205*.txt'
gci $fileToZip -File | Compress-Archive -DestinationPath $zipFN -Update
Upvotes: 1
Reputation: 10034
Since * isn't an accepted character. You could replace your $filesToZip with a Get-ChildItem and a filter and then iterate through the values with a foreach.
Add-Type -assembly 'System.IO.Compression'
Add-Type -assembly 'System.IO.Compression.FileSystem'
[string]$zipFN = 'c:\temp\myZipFile.zip'
$filesToZip = (Get-ChildItem -Path "c:\temp\" -Filter test.*).fullname
[System.IO.Compression.ZipArchive]$ZipFile = [System.IO.Compression.ZipFile]::Open($zipFN,([System.IO.Compression.ZipArchiveMode]::Create))
foreach ($fileToZip in $filesToZip) {
[System.IO.Compression.ZipFileExtensions]::CreateEntryFromFile($ZipFile, $fileToZip, (Split-Path $fileToZip -Leaf))
}
$ZipFile.Dispose()
Upvotes: 1