Mats codemix

Mats codemix

A little c#, a litte .NET and throw in some c++ and you get a nice Spaghetti

Mats codemix RSS Feed
 
 
 
 

Calling 7-Zip from powershell

I had to write a little utility-script to backup and restore some files used for testdata. First i tried a commandline plugin for IZarc which seemed to select the wrong set of files…

I decided to use 7-Zip after reading this post:John Robbins blog which helped me with the -o option.

What i struggled with was how to call 7-Zip, but The PowerShell Guy came to my rescue.

So here is my little example script to call 7-Zip from powershell.

# Alias for 7-zip
if (-not (test-path "$env:ProgramFiles\7-Zip\7z.exe")) {throw "$env:ProgramFiles\7-Zip\7z.exe needed"}
set-alias sz "$env:ProgramFiles\7-Zip\7z.exe"
 
# directories to use
$base = 'C:\dev\ps\ziptest\'
$Extract = 'C:\dev\ps\ziptest\to dir\'
$zipdir = 'C:\dev\ps\ziptest\zip dir\'
 
# Zip-file name
$yy = "test"
$zipfile = $zipdir + 'zz' + $yy+ '.zip'
$zipoption = ' -tzip "' + $zipfile + '"'
 
# Files to compress
$from = $base + "from\*.*"
 
# Create zip-file
write-host "from:" $from
write-host "zipopt:" $zipoption
 
remove-item "$zipfile"
sz a -tzip "$zipfile" $from
 
# Extract files from archive
 
# Since the -o option to 7Z.EXE cannot have a space between it and the
# directory there's a bit of a problem. PowerShell does not expand the
# line -o$Extract if passed directly on the command line.
# John Robbins blog
# http://www.wintellect.com/cs/blogs/jrobbins/archive/2008/04/20/easily-downloading-and-installing-the-sysinternals-suite.aspx
$outputOption = "-o$Extract"
Write-Output "Extracting files into $Extract"
write-host "output:" $outputOption
sz e -tzip "$zipfile" $outputOption -y
 
# Show contents of archive
sz l -tzip "$zipfile"

Leave a Reply