首页 > 解决方案 > 使用 powershell 将 zip 文件解压缩到多个文件夹中

问题描述

我分别有 5 个 zip 文件和 5 个文件夹。文件有:FranceData.zip、USAdata.zip、GermanData.zip、Italydata.zip 和 DanemarkData.zip。文件夹有:FranceFolder、USAFolder、GermanFolder、ItalyFolder 和 DanemarkFolder。我想知道如何使用 Powershell 中的 Array 将这些文件解压缩到它们各自的文件夹中。我知道 Powershell 并且需要帮助。谢谢

标签: powershell

解决方案


这可以使用Expand-ArchivePowerShell 5 及更高版本中提供的 cmdlet 来完成。(可以通过$PSVersionTable变量检查 PowerShell 的版本。)

要将 zip 文件提取到特定文件夹,请使用以下语法:

Expand-Archive -Path 'ZipFile.zip' -DestinationPath 'ZipFolder'

或者

Expand-Archive -LiteralPath 'ZipFile.zip' -DestinationPath 'ZipFolder'

如果使用该参数,PowerShell 会将, , ,-Path等字符识别为通配符,这可能会导致包含方括号的文件路径出现意外行为。 如果使用该参数,PowerShell 不会将任何字符视为通配符。*?[]
-LiteralPath


假设您所有的 zip 文件和文件夹都遵循相同的命名模式,您可以使用这样的数组:

$Countries = @(
    'France',
    'USA',
    'German'
    'Italy',
    'Danemark'
)

foreach ($Country in $Countries)
{
    $ZipFilePath = $Country + 'Data.zip'
    $DestinationPath = $Country + 'Folder'

    Expand-Archive -LiteralPath $ZipFilePath -DestinationPath $DestinationPath
}

如果您的文件和文件夹不遵循相同的命名模式,您可以使用字典(或KeyValuePairs 的集合),如下所示:

$ZipFilesAndFolders = @{
    'FranceData.zip' = 'FranceFolder'
    'USAData.zip' = 'USAFolder'
    'GermanData.zip' = 'GermanFolder'
    'ItalyData.zip' = 'ItalyFolder'
    'DanemarkData.zip' = 'DanemarkFolder'
}

foreach ($KeyAndValue in $ZipFilesAndFolders.GetEnumerator())
{
    $ZipFilePath = $KeyAndValue.Key
    $DestinationPath = $KeyAndValue.Value

    Expand-Archive -LiteralPath $ZipFilePath -DestinationPath $DestinationPath
}

使用 PowerShell 4(和 3)

如果您安装了 .Net Framework 4.5,则可以使用Microsoft.PowerShell.Archive由 PowerShell 团队创建的。
PowerShell 4 需要 .Net Framework 4.5,因此无需任何系统更改即可工作。
该模块可以在https://github.com/PowerShell/Microsoft.PowerShell.Archive找到

使用的语法是相同的,函数是Expand-Archive,参数是-Path-LiteralPath-DestinationPath
只需确保在使用之前已导入模块,这可以使用Import-Modulecmdlet 来完成,如下所示:

Import-Module -Name 'Microsoft.PowerShell.Archive' -Force

PowerShell 2

可以在此处找到 PowerShell 2 的解决方案:https ://stackoverflow.com/a/37814462/9447234


推荐阅读