从PowerShell脚本中运行7-Zip

r7s23pms  于 2022-11-10  发布在  Shell
关注(0)|答案(7)|浏览(265)

我正在尝试使用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"

当直接粘贴到命令窗口中时,其工作方式与预期相同。我试图弄清楚这一点已经有一段时间了,但假设我遗漏了什么(可能非常明显)。有没有人知道我需要做些什么才能让这一切顺利进行?

tct7dpnv

tct7dpnv1#

找到了this脚本,并根据您的需要进行了调整。你能不能试一下:

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

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

Set-Alias Start-SevenZip $7zipPath

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

Start-SevenZip a -mx=9 $Target $Source
qfe3c7zg

qfe3c7zg2#

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

2vuwiymt

2vuwiymt3#

只需在命令前面加上与号即可

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

mrzz3bfm4#

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

cmd /c 7za ...
rn0zuynd

rn0zuynd5#

如果调整正确:不要忘记“$Target”上的“”,并避免在c:\Programm文件中路径中有空格的$7zipPath

Set-Alias 7zip $7zipPath

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

7zip a -mx=9 "$Target" "$Source"

7z a "$ArchiveName" -t7z '@listfile.txt'
v440hwme

v440hwme6#

尝试使用参数文件指定程序或脚本的位置:
-文件“C:\Program Files\someting.exe”

s1ag04yj

s1ag04yj7#

C:\'Program files'\7-Zip\7z.exe a '$archiveFile'  -Path '$dest'

其中:

  • archiveFile=存档文件名的名称。
  • dest=目标文件夹。

相关问题