【问题标题】:Powershell Unzip One Specific Folder in a File with Dynamic NamePowershell 将一个特定文件夹解压缩到具有动态名称的文件中
【发布时间】:2020-02-04 22:00:07
【问题描述】:

我发现了一段代码here 几乎可以满足我的需要,即从存档文件中仅提取一个文件夹。

我唯一遇到的问题是存档名称每月都会更改,因此我想使用通配符。一旦指定了通配符($zipfile 中的 *),该脚本对我不起作用。

如果有任何建议,我将不胜感激。

[Reflection.Assembly]::LoadWithPartialName('System.IO.Compression.FileSystem') | Out-Null

$zipfile = 'C:\ALL\Debtor*.zip'
$folder  = 'tmp\st\sd'
$dst     = 'C:\ALL\ZipOutput'

[IO.Compression.ZipFile]::OpenRead($zipfile).Entries | ? {
  $_.FullName -like "$($folder -replace '\\','/')/*.*"
} | % {
 $file   = Join-Path $dst $_.FullName
 $parent = Split-Path -Parent $file
 if (-not (Test-Path -LiteralPath $parent)) {
  New-Item -Path $parent -Type Directory | Out-Null
}
[IO.Compression.ZipFileExtensions]::ExtractToFile($_, $file, $true)

【问题讨论】:

    标签: powershell wildcard unzip


    【解决方案1】:

    试试这个尺寸。只需使用 Get-ChildItem 在您的 ALL 目录中找到 zip 文件。

    [Reflection.Assembly]::LoadWithPartialName('System.IO.Compression.FileSystem') | Out-Null
    
        $zipfile = Get-ChildItem -Path C:\ALL\ -Filter *.zip | Where-Object {$_.Name -like "Debtor*"} | Select-Object -ExpandProperty FullName
        $folder  = 'tmp\st\sd\'
        $dst     = 'C:\ALL\ZipOutput'
    
        [IO.Compression.ZipFile]::OpenRead($zipfile).Entries | Where-Object {
            $_.FullName -like "$($folder -replace '\\','/')/*.*"
        } | ForEach-Object {
            $file   = Join-Path $dst $_.FullName
            $parent = Split-Path -Parent $file
    
            if(-not (Test-Path -LiteralPath $parent)) {
                New-Item -Path $parent -Type Directory | Out-Null
            }
            [IO.Compression.ZipFileExtensions]::ExtractToFile($_, $file, $true)
        }
    

    我还假设存档名称发生更改,但没有多个具有该名称的存档。如果有,您需要将所有内容包装在 Foreach($zip in $zipfile){ ... }

    【讨论】:

    • 我收到此错误:Exception calling "OpenRead" with "1" argument(s): "Path cannot be null. Parameter name: path" At line:7 char:5 + [IO.Compression.ZipFile]::OpenRead($zipfile).Entries | Where-Obje ... + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : NotSpecified: (:) [], MethodInvocationException + FullyQualifiedErrorId : ArgumentNullException
    • @user8449681 我刚刚修复了代码。请再试一次。我添加了-ExpandProperty Fullname。以前要访问您必须使用的值 $zipfile.fullname
    • 现在可以用了,非常感谢!!我唯一做的另一件事是从 $folder 值中删除了最后一个 \。
    猜你喜欢
    • 2012-02-14
    • 2021-10-14
    • 1970-01-01
    • 1970-01-01
    • 2013-12-29
    • 1970-01-01
    • 2015-12-26
    • 2020-05-02
    • 1970-01-01
    相关资源
    最近更新 更多