Powershell to Create a zip (or 7z) of each file in a folder then delete original file

ぃ、小莉子 提交于 2020-01-25 02:30:47

问题


I have a folder with a Ton of iso images. I've found that a lot of the images have dummy data in them to reach the size of the original DVD. I can save an enormous amount of space by zipping them up. I tried creating a batch file but it failed to work properly.

So, I basically want it to create a .7z for each file in a folder, then delete the original file.

Here's what I got. It zips the files but it fails on removable of the files afterwards. Can't figure out why:

function zipFiles()
 {
 dir *.iso| ForEach-Object { & "7z.exe" a -mx9 $_.BaseName $_.Name } 
 }

function delFiles()
 {
 dir *.iso| ForEach-Object { & Remove-Item $_.BaseName $_.Name } 
 }

zipFiles
delFiles

回答1:


Try adding -force to the remove-item




回答2:


Change your delFiles function:

function delFiles()
 {
     dir *.iso| ForEach-Object { Remove-Item $_.FullName } 
 }



回答3:


Try this:

pushd C:\...[path to folder]
for /r %%a in (*) do (
if "%%~xa"==".iso" (
7z a "%%~na.zip" "%%~a"
if exist "%%~na.zip" (
Del "%%~na.iso"
)
)
)
popd

Note: I seriously recommend putting an Echo before the 7z and Del Commands to see what the program will do before running it. If you notice I made it only compress .iso files.

Lastly I would recommend using this program instead:

pushd C:\...[path to folder]
7z a Images.zip *.iso
Echo.&Echo Check all the files are compressed
pause
del *.iso
popd

Which will compress them all into 1 .zip file which can be opened in explorer and indivdual files can still be accesed. It will also improve the compression ratio. And again I recommend first checking all files are compressed before continuing in the middle pause command.

Look at the 7-zip.chm file for more help in the 7-zip folder.




回答4:


I think a solution is here:

Superuser - 7-Zip script to delete after zipping



来源:https://stackoverflow.com/questions/21517458/powershell-to-create-a-zip-or-7z-of-each-file-in-a-folder-then-delete-original

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