【问题标题】:find all specific folders and zip them找到所有特定文件夹并压缩它们
【发布时间】:2017-05-17 04:09:55
【问题描述】:

当然,我想找到所有名称为“test”的文件夹并将它们压缩到具有不同名称的单个文件夹中。

我设法做了一些代码:

$RootFolder = "E:\"
$var = Get-ChildItem -Path $RootFolder -Recurse |
       where {$_.PSIsContainer -and $_.Name -match 'test'}

#this is assembly for zip functionality
Add-Type -Assembly "System.IO.Compression.Filesystem"

foreach ($dir in $var) {
    $destination = "E:\zip\test" + $dir.Name + ".zip"

    if (Test-Path $destination) {Remove-Item $destination}

    [IO.Compression.Zipfile]::CreateFromDirectory($dir.PSPath, $destination)
}

它给了我一个错误:

使用“2”参数调用“CreateFromDirectory”的异常:“不支持给定路径的格式。”

我想知道,传递我的$dir 路径的正确方法是什么。

【问题讨论】:

    标签: powershell powershell-5.0


    【解决方案1】:

    Get-ChildItem 返回的PSPath 属性以PSProvider 为前缀。 CreateFromDirectory() method 有两个字符串;第一个是sourceDirectoryName,您可以使用对象中的Fullname

    $RootFolder = "E:\"
    $Directories = Get-ChildItem -Path $RootFolder -Recurse | Where-Object {
        $_.PSIsContainer -And
        $_.BaseName -Match 'test'
    }
    
    Add-Type -AssemblyName "System.IO.Compression.FileSystem"
    
    foreach ($Directory in $Directories) {
        $Destination = "E:\zip\test$($Directory.name).zip"
    
        If (Test-path $Destination) {
            Remove-Item $Destination
        }
    
        [IO.Compression.ZipFile]::CreateFromDirectory($Directory.Fullname, $Destination) 
    }
    

    【讨论】:

    • 谢谢! Fullnamepropery 让我很困惑,我没想到这实际上是一条路径!
    【解决方案2】:

    如果您使用的是 v5,我建议您使用 Commandlet

    如果您不想使用命令行开关,可以使用:

    $FullName = "Path\FileName"
    $Name = CompressedFileName
    $ZipFile = "Path\ZipFileName"
    $Zip = [System.IO.Compression.ZipFile]::Open($ZipFile,'Update')
    [System.IO.Compression.ZipFileExtensions]::CreateEntryFromFile($Zip,$FullName,$Name,"optimal")
    $Zip.Dispose()
    

    【讨论】:

    • 我喜欢Dispose方法,我会试试看! Tnx。
    【解决方案3】:

    如果你有这样的文件夹结构:

    - Folder1
     -- Test
    - Folder2
     -- Test
    - Folder3
     -- Test
    

    你可以这样做:

    gci -Directory -Recurse -Filter 'test*' | % {
        Compress-Archive "$($_.FullName)\**" "$($_.FullName -replace '\\|:', '.' ).zip"
    }
    

    你会得到:

    D..Dropbox.Projects.StackOverflow-Posh.ZipFolders.Folder1.Test.zip D..Dropbox.Projects.StackOverflow-Posh.ZipFolders.Folder2.Test.zip D..Dropbox.Projects.StackOverflow-Posh.ZipFolders.Folder3.Test.zip

    或者,如果您想保留 zip 中的目录结构:

    gci -Directory -Recurse -Filter 'test*' | % {
            Compress-Archive $_.FullName "$($_.FullName -replace '\\|:', '.' ).zip"
        }
    

    【讨论】:

      猜你喜欢
      • 2011-08-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-05-30
      • 2022-10-04
      • 1970-01-01
      • 2019-03-23
      相关资源
      最近更新 更多