Passing Variable to 7zip from powershell

3.2k views Asked by At

I can see that the there have been similar question answered but nothing seems to have the answers I'm looking for, I have tried using the solutions/modifying them to suit my needs but am unable to get the correct outputs.

My main question is: Can you pass Powershell variables to 7zip's command line.

Currently i have the script:

##########Alias Setting##########
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"

############################################
#### Variables 

$filePath = "D:\Logs\test\201310\" #location to look in

$Archive = "D:\Logs\Test\201310\"

$Extension = "*.log" #extensions to look for

$Days = "30" #Number of days past today's date that will be archived

$CutDay = [DateTime]::Now.AddDays($Days)

$log = Get-ChildItem $filepath -include $Extension -recurse | Where-Object {$_.LastWriteTime -lt $CutDay}

########### END of VARABLES ##################

 foreach ($File in $log)   #current gui output - temp only using for debugging purpose if required and to confirm files.
    {
        write-host "File Name : $File " $File.LastWriteTime 
    }

    foreach ($file in $log) # actually zipping
   {
    $archivename = $_.CutDay
      sz a -t7z $archivename $archivename -m0=PPMd
   }

########### END OF SCRIPT ##########

What i would like to have is have the 7zip command line read the file name and destination from variables, I plan to try and make this as a generic script as possible so the $archivename would depend on folder name and current date.

I would like the script to be able to read the locations it is zipping via parameters but currently I cannot get it to read the variables!

Any help would be appreciate or if you require clarification please let me know.

1

There are 1 answers

7
Martin Brandl On BEST ANSWER

I figured out that the best way to pass parameter to an executable is using the splatting parameter (@variablename):

$7zipPath = "$env:ProgramFiles\7-Zip\7z.exe"

$parameter = @('a', '-t7z', '-m0=PPMd', "$target", "$source")
&$7zipPath @parameter

sz a -t7z $archivename $archivename -m0=PPMd

There are two $archivename variables you pass to 7zip. The first should be the Target (e.g. c:\test.zip) and the second the Source (e.g c:\test.text)