Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
379 views
in Technique[技术] by (71.8m points)

7zip - Running 7-Zip from within a Powershell script

I'm trying to use 7-Zip to backup some files inside a Powershell (v2) script.

I have:

$zipPath = "C:Program Files7-Zip7z.exe"
[Array]$zipArgs = "-mx=9 a", "`"c:BackupFolderackup.zip`"", "`"c:BackupFromackMeUp.txt`""

&$zipPath $zipArgs;

But when I run this I get:

7-Zip [64] 9.20  Copyright (c) 1999-2010 Igor Pavlov  2010-11-18


Error:
Incorrect command line

Writing this to the screen I get:

C:Program Files7-Zip7z.exe -mx=9 a "c:BackupFolderackup.zip" "c:BackupFromackMeUp.txt"

So I assumed that I needed to put quotes around the path to 7z.exe, that gave me:

$zipPath = "C:Program Files7-Zip7z.exe"
$zipPath = " `"$zipPath`" "
[Array]$zipArgs = "-mx=9 a", "`"c:BackupFolderackup.zip`"", "`"c:BackupFromackMeUp.txt`""

&$zipPath $zipArgs;     

But then I get the following error:

    The term '"C:Program Files7-Zip7z.exe"' is not recognized as the name of a cmdlet, function, script file
, or operable program. Check the spelling of the name, or if a path was included, verify that the path is c
orrect and try again.
At C:BackupScriptBackup.ps1:45 char:22
+                     & <<<< `"$zipPath`" $zipArgs;                    
    + CategoryInfo          : ObjectNotFound: ("C:Program Files7-Zip7z.exe":String) [], CommandNotFound 
   Exception
    + FullyQualifiedErrorId : CommandNotFoundException

Writing it out gives me:

"C:Program Files7-Zip7z.exe" -mx=9 a "c:BackupFolderackup.zip" "c:BackupFromackMeUp.txt"

Which works as expected when pasting straight into a command window. I have been trying to figure this out for a while, but assume I am missing something (probably quite obvious). Can anybody see what I need to do to make this run?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Found this script and adapted it to your needs. Can you please try:

$7zipPath = "$env:ProgramFiles7-Zip7z.exe"

if (-not (Test-Path -Path $7zipPath -PathType Leaf)) {
    throw "7 zip file '$7zipPath' not found"
}

Set-Alias 7zip $7zipPath

$Source = "c:BackupFromackMeUp.txt"
$Target = "c:BackupFolderackup.zip"

7zip a -mx=9 $Target $Source

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...