Powershell system.io.compression压缩文件和/或文件夹

Powershell system.io.compression压缩文件和/或文件夹,powershell,io,compression,system,Powershell,Io,Compression,System,我在工作中制作一些自动化任务,需要压缩某些文件和/或文件夹。 我要做的是在文件夹1中压缩文本文件,其中包含4个txt文件 执行此命令会出现错误,但仍会压缩txt文件: Exception calling "CreateFromDirectory" with "4" argument(s): "The directory name is invalid. " At line:15 char:13 + [System.IO.Compression.ZipFile]::Crea

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

执行此命令会出现错误,但仍会压缩txt文件:

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开关而不是include。 这不会产生任何错误消息。
有什么建议吗?

@DavidBrabant说得对,在路径中放置通配符是不正常的,但我认为在这种情况下,您可以通过foreach语句传递结果

我认为问题在于,的第一个参数应该是目录名,但您已经向它传递了一个文件名。变量名($Source和$Source)的使用并没有真正起到帮助作用

调用
CreateFromDirectory
时,它将包含第一个zip文件的全名,原因如下:

$Source = $_.fullName
我猜,由于您有一个过滤器“*.txt”,您希望将单个文件而不是整个文件夹添加到一个zip文件中,那么这就有点复杂了。有关示例,请参见此处:

但如果您只是想压缩文件夹,请使用:

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

您的源目录名无效。它应该是:“C:\folder1”(不带通配符)如果没有通配符,它将不会列出文件夹中的txt文件。请使用-filter而不是-include。Include用于过滤路径。其作用完全相同。压缩文件但为每个文件生成一个错误ZippeEdit:它创建zip但不压缩文件唯一的问题是,我希望它使用自己的原始名称压缩。另外,我只想要一些压缩的文件,不需要文件夹。这一个有效:Get-ChildItem“C:\temp\test”-目录| foreach{$Folder=$\\全名[System.IO.Compression.ZipFile]::CreateFromDirectory($Folder,$Folder.zip,$compressionLevel,$ExcludeBaseDirectory)我该如何增加压缩以使文件更小?@NigelFds-读一读和@DavidMartin谢谢这正是我想要的,干杯