compression压缩文件和

compression压缩文件和

本文介绍了Powershell system.io.compression压缩文件和/或文件夹的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在工作中生成一些自动化任务,我需要压缩某些文件和/或文件夹。
我想要做的是获取zip文件夹1中包含4个txt文件的文本文件。

Im producing some automated tasks at work where i need to zip certain files and/or folders.What im trying to do is getting zip the text files in folder 1 which contains 4 txt files.

执行此命令会出错但仍会拉链txt files:

Executing this command gives an error but still zips the txt files :

Exception calling "CreateFromDirectory" with "4" argument(s): "The directory name is invalid.
"
At line:15 char:13
+             [System.IO.Compression.ZipFile]::CreateFromDirectory($Source, "$Sour ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo          : NotSpecified: (:) [], MethodInvocationException

我现在得到的是:

[Reflection.Assembly]::LoadWithPartialName( "System.IO.Compression.FileSystem" )
$includeBaseDirectory = $false
$compressionLevel= [System.IO.Compression.CompressionLevel]::Optimal

$source = "C:\folder1\*"
Get-ChildItem $source -include *.txt  |
Foreach {
        $Source = $_.fullName
        [System.IO.Compression.ZipFile]::CreateFromDirectory    ($Source, "$Source.zip",$compressionLevel, $includebasedirectory)
        }

此外,如果我想压缩folder1中的文件夹,我使用-directory switch而不是include。
不会产生任何错误消息。
有什么建议吗?

Also if i want to zip the folders inside folder1 i use -directory switch instead of include.that doesnt produce any error messages.any suggestions?

推荐答案

@DavidBrabant是正确的,将通配符放在路径中是正常的,但是我认为你可以在这种情况下逃脱它,因为你通过foreach声明来管理结果。

@DavidBrabant is right that it is not normal to put the wildcard in the path, but I think you can get away with it in this instance as you are piping the results through a foreach statement.

我认为问题是你的第一个参数应该是一个目录名,但你已经传递了一个文件名。使用变量名称($ Source和$ source)确实没有帮助。

I believe the problem is that your first parameter of CreateFromDirectory should be a directory name, but you have passed it a filename. This isn't really helped by the use of variable names ($Source and $source).

当你打电话给 CreateFromDirectory 它将包含第一个zip文件的全名,因为以下行:

When you call CreateFromDirectory it will contain the full name to the first zip file because of the following line:

$Source = $_.fullName

我猜你有一个过滤器'* .txt'你要添加单个文件而不是整个文件夹到一个zip文件然后它更多涉及。请参阅此处以获取示例:

I'm guessing that as you have a filter '*.txt' you want to add individual files rather than the whole folder to a zip file then it is a little more involved. See here for an example: http://msdn.microsoft.com/en-us/library/hh485720(v=vs.110).aspx

但是如果你只是想压缩文件夹然后使用:

But if you simply want to zip the folder then use:

$sourceFolder = "C:\folder1"
$destinationZip = "c:\zipped.zip"
[Reflection.Assembly]::LoadWithPartialName( "System.IO.Compression.FileSystem" )
[System.IO.Compression.ZipFile]::CreateFromDirectory($sourceFolder, $destinationZip)

这篇关于Powershell system.io.compression压缩文件和/或文件夹的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-03 03:27