Running 7-Zip from within a Powershell script

空扰寡人 提交于 2019-11-27 15:37:56

问题


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

I have:

$zipPath = "C:\Program Files\7-Zip\7z.exe"
[Array]$zipArgs = "-mx=9 a", "`"c:\BackupFolder\backup.zip`"", "`"c:\BackupFrom\backMeUp.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 Files\7-Zip\7z.exe -mx=9 a "c:\BackupFolder\backup.zip" "c:\BackupFrom\backMeUp.txt"

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

$zipPath = "C:\Program Files\7-Zip\7z.exe"
$zipPath = " `"$zipPath`" "
[Array]$zipArgs = "-mx=9 a", "`"c:\BackupFolder\backup.zip`"", "`"c:\BackupFrom\backMeUp.txt`""

&$zipPath $zipArgs;     

But then I get the following error:

    The term '"C:\Program Files\7-Zip\7z.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:\BackupScript\Backup.ps1:45 char:22
+                     & <<<< `"$zipPath`" $zipArgs;                    
    + CategoryInfo          : ObjectNotFound: ("C:\Program Files\7-Zip\7z.exe":String) [], CommandNotFound 
   Exception
    + FullyQualifiedErrorId : CommandNotFoundException

Writing it out gives me:

"C:\Program Files\7-Zip\7z.exe" -mx=9 a "c:\BackupFolder\backup.zip" "c:\BackupFrom\backMeUp.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?


回答1:


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

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

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

Set-Alias 7zip $7zipPath

$Source = "c:\BackupFrom\backMeUp.txt"
$Target = "c:\BackupFolder\backup.zip"

7zip a -mx=9 $Target $Source



回答2:


put "&" special character before 7z command. Example: &7z ...




回答3:


Maybe a simpler solution is to run 7-zip on your Powershell via cmd:

cmd /c 7za ...



回答4:


Simply prefix the command with an ampersand

& "C:\Program Files\7-Zip\7z.exe" -mx=9 a "c:\BackupFolder\backup.zip" "c:\BackupFrom\backMeUp.txt"



回答5:


try to use parameter -file to specify the location of program or script:

-file "C:\Program Files\someting.exe"



来源:https://stackoverflow.com/questions/25287994/running-7-zip-from-within-a-powershell-script

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!