【问题标题】:Need Powershell Script for ZIP Extraction of only Specific Folder containing Style.CSS?需要 Powershell 脚本来提取仅包含 Style.CSS 的特定文件夹的 ZIP?
【发布时间】:2013-01-06 23:46:15
【问题描述】:

需要 Powershell 脚本来仅提取包含 Style.CSS 的特定文件夹的 ZIP 文件吗?

我有许多包含文件夹和文件的 ZIP 文件。我需要一个脚本来仅从 ZIP 文件中过滤和提取包含 Style.CSS 的整个文件夹。

有一个similar one 使用 DotNetZip,但不能完全检测到包含 Style.css 的未知文件夹名称,然后仅提取该文件夹。

请指教。谢谢。

【问题讨论】:

    标签: powershell zip extract unzip extraction


    【解决方案1】:

    这是一种帮助您入门的方法,使用 .Net Framework 4.5 的 ZipFile and ZipFileExtensions 类:

    Add-Type -Assembly System.IO.Compression.FileSystem
    
    foreach($sourcefile in (Get-ChildItem -filter "*.zip"))
    {
        Write-Host "Processing $sourcefile"
        $entries = [IO.Compression.ZipFile]::OpenRead($sourcefile.FullName).Entries
    
        #first pass to collect the paths of the folders with a Style.CSS file 
        $folders = $entries |
            ?{ $_.Name -eq 'Style.CSS' } |
            %{ split-path $_.FullName } | unique
    
        #second pass to extract just the files in those folders
        $entries |
            ?{ (split-path $_.FullName) -in @($folders) -and $_.Name } |
            %{
                #compose some target path
                $targetpath = join-path "$targetroot" (join-path $sourcefile.Name $_.FullName)
                #create its directory
                md (split-path $targetfilename) >$null 2>&1
                #extract the file (and overwrite)
                [IO.Compression.ZipFileExtensions]::ExtractToFile($_, $targetfilename, $true)
            }
    }
    

    只需定义一些 targetroot 或编写另一个 targetpath...

    【讨论】:

    • 感谢您提供详细的脚本。我会检查它/测试它。 PS:我熟悉批处理文件,过去也做过 .NET 编程和一些 VBS。我还没有真正使用过 PowerShell。我将您的代码保存到什么样的文件中?并执行?
    • 你可以把上面的例如在文件myscript.ps1 中。然后要执行它,您可以运行powershell -f path_to\myscript.ps1 或为此创建快捷方式;在 powershell 中,您可以使用 & 'path_to\myscript.ps1' 运行它。
    • 非常感谢。我可以在没有 .NET 4.5 的情况下使用这个脚本和逻辑吗?使用其他具有类似能力的工具/库?如下建议的 7zip 或 DotNetZip?
    【解决方案2】:

    如果 .NET 4.5 不是一个选项,请使用 7zip: http://sevenzip.sourceforge.jp/chm/cmdline/commands/extract.htm

    【讨论】:

    • 我的机器上还没有 NET 4.5。我有 7zip。如何编写类似于@mousio 概述的基于 .NET 4.5 的代码的“必需逻辑”(在 Zip 文件中搜索正确的文件/文件夹位置)编写脚本
    猜你喜欢
    • 1970-01-01
    • 2014-03-02
    • 1970-01-01
    • 2020-04-02
    • 2015-11-20
    • 2019-02-05
    • 2013-12-14
    • 1970-01-01
    • 2023-03-19
    相关资源
    最近更新 更多