我正在尝试使用 powershell 将文件添加到 zip 文件
我可以创建 zip 文件,但不知道如何将我的文件添加到其中
我正在使用
$zipfilename = 'c:\cwRsync\backup.zip'
$file = 'c:\cwRsync\backup.log'
set-content $zipfilename ("PK" + [char]5 + [char]6 + ("$([char]0)" * 18))
(dir $zipfilename).IsReadOnly = $false
$zipfile = (New-Object -ComObject shell.application).NameSpace($zipfilename)
$zipfile.MoveHere($file.FullName)
Run Code Online (Sandbox Code Playgroud)
这会创建 zip 文件,但不会添加新文件
我尝试了在 stackoverflow 上找到的以下代码,该代码有效
$zipfilename = "a.zip"
set-content $zipfilename ("PK" + [char]5 + [char]6 + ("$([char]0)" * 18))
$app = new-object -com shell.application
$zip = ( get-item a.zip ).fullname
$folder = $app.namespace( $zip )
$item = new-item file.txt -itemtype file -value "Mooo" -force
$folder.copyhere( $item.fullname )
Run Code Online (Sandbox Code Playgroud)
但是添加了一个由 powershell 创建的文件,而我想添加一个现有文件
任何帮助将非常感激
Zim*_*mba 14
要创建 zip 存档:
powershell Compress-Archive %file% %file%.zip
Run Code Online (Sandbox Code Playgroud)
要替换存档(使用不同的文件):
powershell Compress-Archive -force %different_file% %file%.zip
Run Code Online (Sandbox Code Playgroud)
要将文件添加到(现有)存档:
powershell Compress-Archive -update %2nd_file% %file%.zip
Run Code Online (Sandbox Code Playgroud)
在 Win 10 CMD Powershell 5.1 上测试
该CopyHere函数仅接受一个字符串,该字符串是文件的路径。例如:
$folder.copyhere( "c:\PathToYourFile\YourFile" )
Run Code Online (Sandbox Code Playgroud)
编辑:下面提示中提到的 Powershell Pack 不再可用。我把它留在这里,以防有人可以找到它存档在某处,并可以用链接更新这篇文章。
提示:
Powershell Pack 模块有一些有用的工具,其中之一是 zip 实用程序,它会将您的代码减少到 1 行:
Copy-ToZip "c:\PathToYourFile\YourFile" -ZipFile a.zip
Run Code Online (Sandbox Code Playgroud)