在Powershell脚本中运行7-Zip

问题描述 投票:21回答:5

我正在尝试使用7-Zip备份Powershell(v2)脚本中的一些文件。

我有:

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

&$zipPath $zipArgs;

但是,当我运行这个时,我得到:

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


Error:
Incorrect command line

把它写到屏幕我得到:

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

所以我假设我需要在7z.exe的路径上放置引号,这给了我:

$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;     

但后来我收到以下错误:

    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

写出来给了我:

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

当直接粘贴到命令窗口时,它按预期工作。我一直试图弄清楚这一点,但我想我错过了一些东西(可能很明显)。任何人都可以看到我需要做什么才能让这次运行?

powershell 7zip
5个回答
44
投票

找到this脚本并根据您的需求进行调整。你能试试吗:

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"  

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

sz a -mx=9 $Target $Source

8
投票

在7z命令之前加上“&”特殊字符。示例:&7z ...


2
投票

也许更简单的解决方案是通过cmd在你的Powershell上运行7-zip:

cmd /c 7za ...

0
投票

尝试使用参数-file指定程序或脚本的位置:

-file“C:\ Program Files \ someting.exe”


0
投票

只需使用&符号后缀命令即可

& "C:\Program Files\7-Zip\7z.exe" -mx=9 a "c:\BackupFolder\backup.zip" "c:\BackupFrom\backMeUp.txt"
© www.soinside.com 2019 - 2024. All rights reserved.